From 4190eb54db0562e49f95948c2674337baf29be65 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 8 Nov 2026 14:03:56 -0800 Subject: [PATCH 01/98] Honor @TerminatesExecution on every call that the CFG builds extendWithMethodInvocationNode, rather than visitMethodInvocation, checks the annotation, so it applies also to the desugared call to a try-with-resources statement's close(). --- .../cfg/builder/CFGTranslationPhaseOne.java | 18 +++++------ framework/tests/flow/Termination.java | 32 +++++++++++++++++++ 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 941edb45bf57..f38d665a1454 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -3348,20 +3348,14 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi MethodInvocationNode node = new MethodInvocationNode(tree, target, arguments, getCurrentPath()); - ExtendedNode extendedNode = extendWithMethodInvocationNode(method, node); - - /* Check for the TerminatesExecution annotation. */ - boolean terminatesExecution = - annotationProvider.getDeclAnnotation(method, TerminatesExecution.class) != null; - if (terminatesExecution) { - extendedNode.setTerminatesExecution(true); - } + extendWithMethodInvocationNode(method, node); return node; } /** * Extends the CFG with a MethodInvocationNode, accounting for potential exceptions thrown by the - * invocation. + * invocation. If the method is annotated {@link TerminatesExecution}, the invocation terminates + * execution. * * @param method the invoked method * @param node the invocation @@ -3377,7 +3371,11 @@ private ExtendedNode extendWithMethodInvocationNode( // Add types to account for unchecked exceptions thrownSet.addAll(uncheckedExceptionTypes); - return extendWithNodeWithExceptions(node, thrownSet); + ExtendedNode extendedNode = extendWithNodeWithExceptions(node, thrownSet); + if (annotationProvider.getDeclAnnotation(method, TerminatesExecution.class) != null) { + extendedNode.setTerminatesExecution(true); + } + return extendedNode; } @Override diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index 51dc1334e001..096e0ea10265 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -17,4 +17,36 @@ void t1(@Odd String p1, String p2, boolean b1) { } @Odd String l3 = l1; } + + static class TerminatingCloseable implements AutoCloseable { + @Override + @TerminatesExecution + public void close() { + throw new Error(); + } + } + + // The desugared call to close() does not terminate execution, because a try-with-resources + // statement does not call close() if the resource is null. + void t3(@Odd String p1, String p2, boolean b1, TerminatingCloseable c) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (c) {} + } + // :: error: [assignment] + @Odd String l3 = l1; + } + + // The desugared call to close() terminates execution, because the resource is not null. + void t4(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (TerminatingCloseable c = new TerminatingCloseable()) {} + } + @Odd String l3 = l1; + } } From 0afd0a0fcbd5dc6f7c704bcf268993df61f47cb9 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 8 Nov 2026 19:38:39 -0800 Subject: [PATCH 02/98] Decide whether a receiver may be null in one place A new helper in CFGTranslationPhaseOne, mayBeNull(Node), decides from the receiver node whether a field access, array access, or method call can throw NullPointerException. This is the change of #8445, applied to master (plus #8501) rather than to #8397's branch. --- .../cfg/builder/CFGTranslationPhaseOne.java | 156 +++++++--- .../flow/ReceiverNullPointerException.java | 272 ++++++++++++++++++ framework/tests/flow/Termination.java | 13 + 3 files changed, 397 insertions(+), 44 deletions(-) create mode 100644 framework/tests/flow/ReceiverNullPointerException.java diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index f38d665a1454..9bb66fe7150f 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -284,6 +284,10 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** SwitchBuilder for the current switch. Used to match yield statements to enclosing switches. */ private SwitchBuilder switchBuilder; + /** The switch expressions none of whose results may be null. */ + private final Set neverNullSwitchExpressions = + Collections.newSetFromMap(new IdentityHashMap<>()); + /** * Maps from AST {@link Tree}s to sets of {@link Node}s. Every Tree that produces a value will * have at least one corresponding Node. Trees that undergo implicit conversions, such as boxing @@ -659,6 +663,20 @@ protected void extendWithNode(Node node) { extendWithExtendedNode(new NodeHolder(node)); } + /** + * Extend the list of extended nodes with a node that might throw a {@code NullPointerException}. + * + * @param node the node to add + * @param mayThrowNullPointerException true if the node might throw a {@code NullPointerException} + */ + private void extendWithNode(Node node, boolean mayThrowNullPointerException) { + if (mayThrowNullPointerException) { + extendWithNodeWithException(node, nullPointerExceptionType); + } else { + extendWithNode(node); + } + } + /** * Extend the list of extended nodes with a node, where {@code node} might throw the exception * {@code cause}. @@ -1890,9 +1908,9 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { translateAssignment(indexVariable, new LocalVariableNode(indexVariable), zeroNode); // The array variable is never reassigned, so only the first access to its length can throw - // NullPointerException. Represent that first access before the loop, and the access in the - // loop condition without the exception. - if (mayBeNull(expression)) { + // NullPointerException. Represent that first access before the loop, and represent the + // access in the loop condition without the exception. + if (mayBeNull(expressionNode)) { extendWithArrayLengthAccess(arrayVariable, true); } @@ -1997,6 +2015,72 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { return null; } + /** + * Returns true if the value of the given node may be null. Returns false only if the kind of the + * node guarantees that its value is never null, whatever the values of variables. For example, + * {@code this}, the result of {@code new}, an enum constant, and a call to {@code + * Integer.valueOf} are never null. A type name, as in {@code String.valueOf(x)}, is never null + * because it has no value. + * + * @param node a node of reference type, or a type name + * @return true if the value of the node may be null; false if it is never null + */ + private boolean mayBeNull(Node node) { + if (node instanceof ThisNode + || node instanceof SuperNode + || node instanceof ClassNameNode + || node instanceof ObjectCreationNode + || node instanceof ArrayCreationNode + || node instanceof StringLiteralNode + || node instanceof StringConcatenateNode + || node instanceof FunctionalInterfaceNode) { + return false; + } else if (node instanceof FieldAccessNode fieldAccess) { + // A class literal, a qualified `this`, or an enum constant. + String fieldName = fieldAccess.getFieldName(); + return !(fieldName.equals("class") + || fieldName.equals("this") + || fieldAccess.getElement().getKind() == ElementKind.ENUM_CONSTANT); + } else if (node instanceof MethodInvocationNode invocation) { + return !isBoxedPrimitiveValueOf(invocation.getTarget().getMethod()); + } else if (node instanceof TypeCastNode cast) { + return mayBeNull(cast.getOperand()); + } else if (node instanceof TernaryExpressionNode ternary) { + return mayBeNull(ternary.getThenOperand()) || mayBeNull(ternary.getElseOperand()); + } else if (node instanceof SwitchExpressionNode switchExpression) { + return !neverNullSwitchExpressions.contains(switchExpression); + } else if (node instanceof AssignmentNode assignment) { + return mayBeNull(assignment.getExpression()); + } else { + return true; + } + } + + /** + * Returns true if the given method is a static {@code valueOf} method of a boxed primitive type, + * such as {@code Integer.valueOf}. Such a method never returns null. + * + * @param method a method + * @return true if the method is a static {@code valueOf} method of a boxed primitive type + */ + private static boolean isBoxedPrimitiveValueOf(ExecutableElement method) { + return ElementUtils.isStatic(method) + && method.getSimpleName().contentEquals("valueOf") + && TypesUtils.isBoxedPrimitive(method.getEnclosingElement().asType()); + } + + /** + * Returns true if accessing the given member through the given receiver may throw a {@code + * NullPointerException}. + * + * @param member the accessed field or method + * @param receiver the receiver of the access + * @return true if the access may throw a {@code NullPointerException} + */ + private boolean accessMayThrowNullPointerException(Element member, Node receiver) { + return !ElementUtils.isStatic(member) && mayBeNull(receiver); + } + protected VariableTree createEnhancedForLoopIteratorVariable( MethodInvocationTree iteratorCall, VariableElement variableElement) { TypeMirror iteratorType = TreeUtils.typeOf(iteratorCall); @@ -2041,25 +2125,10 @@ private FieldAccessNode extendWithArrayLengthAccess( handleArtificialTree(lengthSelect); FieldAccessNode lengthAccessNode = new FieldAccessNode(lengthSelect, arrayNode); lengthAccessNode.setInSource(false); - if (mayThrowNullPointerException) { - extendWithNodeWithException(lengthAccessNode, nullPointerExceptionType); - } else { - extendWithNode(lengthAccessNode); - } + extendWithNode(lengthAccessNode, mayThrowNullPointerException); return lengthAccessNode; } - /** - * Returns false if the expression is never null, judging from its syntax. - * - * @param expression an expression of reference type - * @return false if the expression is never null; true if it may be null - */ - private static boolean mayBeNull(ExpressionTree expression) { - expression = TreeUtils.withoutParens(expression); - return !(expression instanceof NewClassTree || expression instanceof NewArrayTree); - } - @Override public Node visitLabeledStatement(LabeledStatementTree tree, Void p) { // This method can set the break target after generating all Nodes in the contained @@ -2124,6 +2193,9 @@ private final class SwitchBuilder { */ private AssignmentNode selectorExprAssignment; + /** True if some result of the switch expression may be null. */ + private boolean someResultMayBeNull = false; + /** * If {@link #switchTree} is a switch expression, then this is a result variable: the synthetic * variable that all results of {@code #switchTree} are assigned to. Otherwise, this is null. @@ -2236,6 +2308,9 @@ private SwitchBuilder(Tree switchTree) { new SwitchExpressionNode( TreeUtils.typeOf(switchTree), switchExpressionTree, switchExprVarUseNode); extendWithNode(switchExpressionNode); + if (!someResultMayBeNull) { + neverNullSwitchExpressions.add(switchExpressionNode); + } return switchExpressionNode; } else { return null; @@ -2404,6 +2479,7 @@ private void buildCase(CaseTree caseTree, int index, boolean isLastCaseOfExhaust extendWithNode(switchExprVarUseNode); Node resultExprNode = scan(resultExpression, null); + someResultMayBeNull |= mayBeNull(resultExprNode); AssignmentTree assign = treeBuilder.buildAssignment(switchExprVarUseTree, resultExpression); handleArtificialTree(assign); @@ -2694,10 +2770,15 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { // A try-with-resources statement calls close() only if the resource is non-null (JLS // 14.20.3.1). A resource variable is final, so it is non-null if its initializer is. - boolean resourceMayBeNull = - !(resourceDeclarationTree instanceof VariableTree variableTree - && variableTree.getInitializer() != null - && !mayBeNull(variableTree.getInitializer())); + boolean resourceMayBeNull = true; + if (resourceDeclarationTree instanceof VariableTree variableTree + && variableTree.getInitializer() != null) { + Set initializerNodes = treeToCfgNodes.get(variableTree.getInitializer()); + resourceMayBeNull = + initializerNodes == null + || initializerNodes.isEmpty() + || initializerNodes.stream().anyMatch(this::mayBeNull); + } Label afterCloseLabel = new Label(); if (resourceMayBeNull) { LiteralTree nullTree = treeBuilder.buildNullLiteral(); @@ -3324,12 +3405,7 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi MethodAccessNode target = new MethodAccessNode(methodSelect, method, receiver); - if (ElementUtils.isStatic(method) || receiver instanceof ThisNode) { - // No NullPointerException can be thrown, use normal node - extendWithNode(target); - } else { - extendWithNodeWithException(target, nullPointerExceptionType); - } + extendWithNode(target, accessMayThrowNullPointerException(method, receiver)); List arguments; if (TreeUtils.isEnumSuperCall(tree)) { @@ -3506,12 +3582,7 @@ public Node visitAssignment(AssignmentTree tree, Void p) { target.setLValue(); Element element = TreeUtils.elementFromUse(variable); - if (ElementUtils.isStatic(element) || receiver instanceof ThisNode) { - // No NullPointerException can be thrown, use normal node - extendWithNode(target); - } else { - extendWithNodeWithException(target, nullPointerExceptionType); - } + extendWithNode(target, accessMayThrowNullPointerException(element, receiver)); // add assignment node assignmentNode = new AssignmentNode(tree, target, expression); @@ -4272,7 +4343,11 @@ public Node visitArrayAccess(ArrayAccessTree tree, Void p) { Node array = scan(tree.getExpression(), p); Node index = unaryNumericPromotion(scan(tree.getIndex(), p)); Node arrayAccess = new ArrayAccessNode(tree, array, index); - extendWithNodeWithExceptions(arrayAccess, arrayAccessExceptionTypes); + extendWithNodeWithExceptions( + arrayAccess, + mayBeNull(array) + ? arrayAccessExceptionTypes + : Collections.singleton(arrayIndexOutOfBoundsExceptionType)); return arrayAccess; } @@ -4298,14 +4373,7 @@ public Node visitMemberSelect(MemberSelectTree tree, Void p) { Node node = new FieldAccessNode(tree, expr); Element element = TreeUtils.elementFromUse(tree); - if (ElementUtils.isStatic(element) - || expr instanceof ImplicitThisNode - || expr instanceof ExplicitThisNode) { - // No NullPointerException can be thrown, use normal node - extendWithNode(node); - } else { - extendWithNodeWithException(node, nullPointerExceptionType); - } + extendWithNode(node, accessMayThrowNullPointerException(element, expr)); return node; } diff --git a/framework/tests/flow/ReceiverNullPointerException.java b/framework/tests/flow/ReceiverNullPointerException.java new file mode 100644 index 000000000000..af85d9cc81f7 --- /dev/null +++ b/framework/tests/flow/ReceiverNullPointerException.java @@ -0,0 +1,272 @@ +import org.checkerframework.framework.testchecker.util.*; + +// Accessing a member of a receiver that is never null does not throw a NullPointerException. +// +// In each method that calls equals(), `l1` is p2 only between `l1 = p2` and the argument `l1 = p1`, +// where the access of `equals` is the only node that could throw a NullPointerException. +public class ReceiverNullPointerException extends ReceiverNullPointerExceptionSuper { + void mayThrow() {} + + void newArray(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + int n = new String[] {l1 = p2}.length; + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void cast(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + int n = ((Object[]) new String[] {l1 = p2}).length; + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void ternary(@Odd String p1, String p2, boolean b) { + String l1 = p1; + try { + mayThrow(); + int n = (b ? new String[] {l1 = p2} : new String[0]).length; + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void enhancedForCast(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + for (String s : (String[]) new String[] {l1 = p2}) { + l1 = p1; + } + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void arrayAccess(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + int n = new int[] {1}[0]; + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void assignment(@Odd String p1, String p2) { + String l1 = p1; + int[] a; + try { + mayThrow(); + l1 = p2; + int n = (a = new int[1]).length; + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void superField(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + Object o = super.f; + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void fieldAssignment(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + ((ReceiverNullPointerExceptionSuper) this).f = p2; + l1 = p1; + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void stringLiteral(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + "abc".equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void stringConcatenation(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + (p2 + p2).equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void superCall(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + super.equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void lambda(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + ((Runnable) () -> {}).equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void methodReference(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + ((Runnable) this::mayThrow).equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void classLiteral(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + String.class.equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + enum Color { + RED + } + + void enumConstant(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + Color.RED.equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + static Color favoriteColor; + + void enumFieldMayBeNull(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + favoriteColor.equals(l1 = p1); + } catch (NullPointerException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } + + void switchExpression(@Odd String p1, String p2, int i) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + (switch (i) { + case 1 -> "a"; + default -> "b"; + }) + .equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + + void switchExpressionMayBeNull(@Odd String p1, String p2, int i, String s) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + (switch (i) { + case 1 -> "a"; + default -> s; + }) + .equals(l1 = p1); + } catch (NullPointerException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } + + void methodCallMayBeNull(@Odd String p1, String p2, String s) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + s.equals(l1 = p1); + } catch (NullPointerException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } + + class Inner { + void qualifiedThis(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + ReceiverNullPointerException.this.equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + } + + void mayBeNull(@Odd String p1, String p2, String[] a) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + int n = a.length; + l1 = p1; + } catch (NullPointerException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } +} + +class ReceiverNullPointerExceptionSuper { + Object f; +} diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index 096e0ea10265..83fbd44d26c4 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -49,4 +49,17 @@ void t4(@Odd String p1, String p2, boolean b1) { } @Odd String l3 = l1; } + + static class SelfClosing extends TerminatingCloseable { + // The desugared call to close() terminates execution, because the resource is not null. + void t5(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (TerminatingCloseable c = this) {} + } + @Odd String l3 = l1; + } + } } From 740820307e61a660ad5b8aa0273bcf725b4d272a Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 8 Nov 2026 19:44:07 -0800 Subject: [PATCH 03/98] Unboxing a never-null value does not throw NullPointerException --- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 9bb66fe7150f..f0a8227a363e 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -914,9 +914,12 @@ protected Node unbox(Node node) { handleArtificialTree(primValueSelect); MethodAccessNode primValueAccess = new MethodAccessNode(primValueSelect, node); primValueAccess.setInSource(false); - // Method access may throw NullPointerException - insertNodeWithExceptionsAfter( - primValueAccess, Collections.singleton(nullPointerExceptionType), node); + if (mayBeNull(node)) { + insertNodeWithExceptionsAfter( + primValueAccess, Collections.singleton(nullPointerExceptionType), node); + } else { + insertNodeAfter(primValueAccess, node); + } MethodInvocationTree primValueCall = treeBuilder.buildMethodInvocation(primValueSelect); handleArtificialTree(primValueCall); From 6938dfa0f3bf7fae0993cc28f38ee0f5159a4931 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 9 Nov 2026 21:01:43 -0800 Subject: [PATCH 04/98] Address review: method-reference NPE edge, enum constants may be null, enhanced-for termination * Creating a bound method reference whose qualifier may be null may throw NullPointerException. * An enum constant may be null when it is read during class initialization. * The synthetic iterator(), hasNext(), and next() calls of an enhanced for loop honor @TerminatesExecution. * Test a try-with-resources whose close() returns normally. --- .../cfg/builder/CFGTranslationPhaseOne.java | 48 ++++++++++++++----- .../flow/ReceiverNullPointerException.java | 25 ++++++++++ framework/tests/flow/Termination.java | 36 ++++++++++++++ 3 files changed, 98 insertions(+), 11 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index f0a8227a363e..2afb94815277 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1799,7 +1799,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - extendWithNode(iteratorCallNode); + extendWithSyntheticMethodInvocationNode(iteratorCallNode); translateAssignment( iteratorVariable, new LocalVariableNode(iteratorVariable), iteratorCallNode); @@ -1828,7 +1828,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( hasNextCall, hasNextAccessNode, Collections.emptyList(), getCurrentPath()); hasNextCallNode.setInSource(false); - extendWithNode(hasNextCallNode); + extendWithSyntheticMethodInvocationNode(hasNextCallNode); extendWithExtendedNode(new ConditionalJump(loopEntry, loopExit)); // Loop body, starting with declaration of the loop iteration variable @@ -1861,7 +1861,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { nextCallNode.setIterableExpression(expression); nextCallNode.setEnhancedForLoop(tree); nextCallNode.setInSource(false); - extendWithNode(nextCallNode); + extendWithSyntheticMethodInvocationNode(nextCallNode); AssignmentNode assignNode = translateAssignment(variable, new LocalVariableNode(variable), nextCall); @@ -2021,8 +2021,9 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { /** * Returns true if the value of the given node may be null. Returns false only if the kind of the * node guarantees that its value is never null, whatever the values of variables. For example, - * {@code this}, the result of {@code new}, an enum constant, and a call to {@code - * Integer.valueOf} are never null. A type name, as in {@code String.valueOf(x)}, is never null + * {@code this}, the result of {@code new}, and a call to {@code Integer.valueOf} are never null. + * An enum constant may be null, because it can be read during class initialization before it is + * assigned. A type name, as in {@code String.valueOf(x)}, is never null * because it has no value. * * @param node a node of reference type, or a type name @@ -2039,11 +2040,9 @@ private boolean mayBeNull(Node node) { || node instanceof FunctionalInterfaceNode) { return false; } else if (node instanceof FieldAccessNode fieldAccess) { - // A class literal, a qualified `this`, or an enum constant. + // A class literal or a qualified `this`. String fieldName = fieldAccess.getFieldName(); - return !(fieldName.equals("class") - || fieldName.equals("this") - || fieldAccess.getElement().getKind() == ElementKind.ENUM_CONSTANT); + return !(fieldName.equals("class") || fieldName.equals("this")); } else if (node instanceof MethodInvocationNode invocation) { return !isBoxedPrimitiveValueOf(invocation.getTarget().getMethod()); } else if (node instanceof TypeCastNode cast) { @@ -3457,6 +3456,25 @@ private ExtendedNode extendWithMethodInvocationNode( return extendedNode; } + /** + * Extends the CFG with a MethodInvocationNode for a call that the CFG builder synthesizes, such + * as the calls to {@code iterator()}, {@code hasNext()}, and {@code next()} in an enhanced for + * loop. Unlike {@link #extendWithMethodInvocationNode}, does not add exceptional edges. If the + * method is annotated {@link TerminatesExecution}, the invocation terminates execution. + * + * @param node the invocation + */ + private void extendWithSyntheticMethodInvocationNode(MethodInvocationNode node) { + addToLookupMap(node); + NodeHolder holder = new NodeHolder(node); + if (annotationProvider.getDeclAnnotation( + node.getTarget().getMethod(), TerminatesExecution.class) + != null) { + holder.setTerminatesExecution(true); + } + extendWithExtendedNode(holder); + } + @Override public Node visitNewClass(NewClassTree tree, Void p) { // see JLS 15.9 @@ -4384,12 +4402,20 @@ public Node visitMemberSelect(MemberSelectTree tree, Void p) { @Override public Node visitMemberReference(MemberReferenceTree tree, Void p) { Tree enclosingExpr = tree.getQualifierExpression(); + Node qualifier = null; if (enclosingExpr != null) { - scan(enclosingExpr, p); + qualifier = scan(enclosingExpr, p); } Node node = new FunctionalInterfaceNode(tree); - extendWithNode(node); + // Creating a bound method reference, such as `expr::method`, throws NullPointerException if + // `expr` is null (JLS 15.13.3). On normal completion, the result is never null. + boolean mayThrowNullPointerException = + qualifier != null + && TreeUtils.MemberReferenceKind.getMemberReferenceKind(tree) + == TreeUtils.MemberReferenceKind.BOUND + && mayBeNull(qualifier); + extendWithNode(node, mayThrowNullPointerException); return node; } diff --git a/framework/tests/flow/ReceiverNullPointerException.java b/framework/tests/flow/ReceiverNullPointerException.java index af85d9cc81f7..dc7b5e49b897 100644 --- a/framework/tests/flow/ReceiverNullPointerException.java +++ b/framework/tests/flow/ReceiverNullPointerException.java @@ -157,6 +157,29 @@ void methodReference(@Odd String p1, String p2) { } } + void boundMethodReferenceMayBeNull(@Odd String p1, String p2, Runnable r) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + ((Runnable) r::run).equals(l1 = p1); + } catch (NullPointerException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } + + void unboundMethodReference(@Odd String p1, String p2) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + ((java.util.function.Function) Object::toString).equals(l1 = p1); + } catch (NullPointerException e) { + @Odd String l3 = l1; + } + } + void classLiteral(@Odd String p1, String p2) { String l1 = p1; try { @@ -179,6 +202,8 @@ void enumConstant(@Odd String p1, String p2) { l1 = p2; Color.RED.equals(l1 = p1); } catch (NullPointerException e) { + // An enum constant is null if it is read during class initialization before it is assigned. + // :: error: [assignment] @Odd String l3 = l1; } } diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index 83fbd44d26c4..164cbf9ecfe7 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -50,6 +50,42 @@ void t4(@Odd String p1, String p2, boolean b1) { @Odd String l3 = l1; } + static class ReturningCloseable implements AutoCloseable { + @Override + public void close() {} + } + + // The desugared call to close() returns normally. + void t4Returning(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (ReturningCloseable c = new ReturningCloseable()) {} + } + // :: error: [assignment] + @Odd String l3 = l1; + } + + static class TerminatingIterable implements Iterable { + @Override + @TerminatesExecution + public java.util.Iterator iterator() { + throw new Error(); + } + } + + // The desugared call to iterator() terminates execution. + void t6(@Odd String p1, String p2, boolean b1, TerminatingIterable it) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + for (String s : it) {} + } + @Odd String l3 = l1; + } + static class SelfClosing extends TerminatingCloseable { // The desugared call to close() terminates execution, because the resource is not null. void t5(@Odd String p1, String p2, boolean b1) { From 2ed40205e150c9df063d4eaf996afa74cc4df063 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 11 Nov 2026 14:40:43 -0800 Subject: [PATCH 05/98] Honor @TerminatesExecution on the desugared calls of an enhanced for loop --- .../cfg/builder/CFGTranslationPhaseOne.java | 25 +++++++++++-- framework/tests/flow/Termination.java | 36 +++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 21e7260deafb..7d188ed0b3e6 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1778,7 +1778,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - extendWithNode(iteratorCallNode); + extendWithSyntheticMethodInvocationNode(iteratorCallNode); translateAssignment( iteratorVariable, new LocalVariableNode(iteratorVariable), iteratorCallNode); @@ -1807,7 +1807,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( hasNextCall, hasNextAccessNode, Collections.emptyList(), getCurrentPath()); hasNextCallNode.setInSource(false); - extendWithNode(hasNextCallNode); + extendWithSyntheticMethodInvocationNode(hasNextCallNode); extendWithExtendedNode(new ConditionalJump(loopEntry, loopExit)); // Loop body, starting with declaration of the loop iteration variable @@ -1840,7 +1840,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { nextCallNode.setIterableExpression(expression); nextCallNode.setEnhancedForLoop(tree); nextCallNode.setInSource(false); - extendWithNode(nextCallNode); + extendWithSyntheticMethodInvocationNode(nextCallNode); AssignmentNode assignNode = translateAssignment(variable, new LocalVariableNode(variable), nextCall); @@ -3390,6 +3390,25 @@ private ExtendedNode extendWithMethodInvocationNode( return extendedNode; } + /** + * Extends the CFG with a MethodInvocationNode for a call that the CFG builder synthesizes, such + * as the calls to {@code iterator()}, {@code hasNext()}, and {@code next()} in an enhanced for + * loop. Unlike {@link #extendWithMethodInvocationNode}, does not add exceptional edges. If the + * method is annotated {@link TerminatesExecution}, the invocation terminates execution. + * + * @param node the invocation + */ + private void extendWithSyntheticMethodInvocationNode(MethodInvocationNode node) { + addToLookupMap(node); + NodeHolder holder = new NodeHolder(node); + if (annotationProvider.getDeclAnnotation( + node.getTarget().getMethod(), TerminatesExecution.class) + != null) { + holder.setTerminatesExecution(true); + } + extendWithExtendedNode(holder); + } + @Override public Node visitNewClass(NewClassTree tree, Void p) { // see JLS 15.9 diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index 096e0ea10265..e0e164184c89 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -49,4 +49,40 @@ void t4(@Odd String p1, String p2, boolean b1) { } @Odd String l3 = l1; } + + static class ReturningCloseable implements AutoCloseable { + @Override + public void close() {} + } + + // The desugared call to close() returns normally. + void t4Returning(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (ReturningCloseable c = new ReturningCloseable()) {} + } + // :: error: [assignment] + @Odd String l3 = l1; + } + + static class TerminatingIterable implements Iterable { + @Override + @TerminatesExecution + public java.util.Iterator iterator() { + throw new Error(); + } + } + + // The desugared call to iterator() terminates execution. + void t6(@Odd String p1, String p2, boolean b1, TerminatingIterable it) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + for (String s : it) {} + } + @Odd String l3 = l1; + } } From 92b24cc69589f0720cf55c5057a285e18a3b44f1 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 11 Nov 2026 14:41:17 -0800 Subject: [PATCH 06/98] Throw NullPointerException for a null receiver after evaluating call arguments A method call tests its receiver for nullness after evaluating its arguments (JLS 15.12.4.4), so the MethodAccessNode no longer throws; the MethodInvocationNode already may throw any RuntimeException. The tests probe receivers through bound method references instead of calls to equals(). --- .../cfg/builder/CFGTranslationPhaseOne.java | 22 +++--- .../flow/ReceiverNullPointerException.java | 74 +++++++++++++------ 2 files changed, 64 insertions(+), 32 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 5e66dc47a191..c7bc06a681cf 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -175,6 +175,7 @@ import org.checkerframework.javacutil.SystemUtil; import org.checkerframework.javacutil.TreePathUtil; import org.checkerframework.javacutil.TreeUtils; +import org.checkerframework.javacutil.TreeUtils.MemberReferenceKind; import org.checkerframework.javacutil.TreeUtilsAfterJava17.CaseUtils; import org.checkerframework.javacutil.TreeUtilsAfterJava17.DeconstructionPatternUtils; import org.checkerframework.javacutil.TypeAnnotationUtils; @@ -2023,8 +2024,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { * node guarantees that its value is never null, whatever the values of variables. For example, * {@code this}, the result of {@code new}, and a call to {@code Integer.valueOf} are never null. * An enum constant may be null, because it can be read during class initialization before it is - * assigned. A type name, as in {@code String.valueOf(x)}, is never null - * because it has no value. + * assigned. A type name, as in {@code String.valueOf(x)}, is never null because it has no value. * * @param node a node of reference type, or a type name * @return true if the value of the node may be null; false if it is never null @@ -3414,12 +3414,15 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi List actualExprs = tree.getArguments(); - // Look up method to invoke and possibly throw NullPointerException + // Look up the method to invoke. The access does not throw a NullPointerException, because the + // receiver is tested for nullness only after the arguments are evaluated. The + // MethodInvocationNode, which follows the arguments, may throw any RuntimeException, including + // a NullPointerException for a null receiver. Node receiver = getReceiver(methodSelect); MethodAccessNode target = new MethodAccessNode(methodSelect, method, receiver); - extendWithNode(target, accessMayThrowNullPointerException(method, receiver)); + extendWithNode(target); List arguments; if (TreeUtils.isEnumSuperCall(tree)) { @@ -4419,14 +4422,15 @@ public Node visitMemberReference(MemberReferenceTree tree, Void p) { qualifier = scan(enclosingExpr, p); } - Node node = new FunctionalInterfaceNode(tree); - // Creating a bound method reference, such as `expr::method`, throws NullPointerException if - // `expr` is null (JLS 15.13.3). On normal completion, the result is never null. + // Creating a bound method reference, such as `expr::method`, throws a NullPointerException if + // the qualifier is null (JLS 15.13.3). Other kinds of member reference have a type or `super` + // as their qualifier. On normal completion, the result is never null. boolean mayThrowNullPointerException = qualifier != null - && TreeUtils.MemberReferenceKind.getMemberReferenceKind(tree) - == TreeUtils.MemberReferenceKind.BOUND + && MemberReferenceKind.getMemberReferenceKind(tree) == MemberReferenceKind.BOUND && mayBeNull(qualifier); + + Node node = new FunctionalInterfaceNode(tree); extendWithNode(node, mayThrowNullPointerException); return node; diff --git a/framework/tests/flow/ReceiverNullPointerException.java b/framework/tests/flow/ReceiverNullPointerException.java index dc7b5e49b897..1abe2bc9493f 100644 --- a/framework/tests/flow/ReceiverNullPointerException.java +++ b/framework/tests/flow/ReceiverNullPointerException.java @@ -2,8 +2,9 @@ // Accessing a member of a receiver that is never null does not throw a NullPointerException. // -// In each method that calls equals(), `l1` is p2 only between `l1 = p2` and the argument `l1 = p1`, -// where the access of `equals` is the only node that could throw a NullPointerException. +// In each method that creates a bound method reference, `l1` is p2 only between `l1 = p2` and +// `l1 = p1`, where creating the method reference is the only node that could throw a +// NullPointerException. public class ReceiverNullPointerException extends ReceiverNullPointerExceptionSuper { void mayThrow() {} @@ -107,7 +108,8 @@ void stringLiteral(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - "abc".equals(l1 = p1); + Runnable r = "abc"::length; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } @@ -118,18 +120,20 @@ void stringConcatenation(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - (p2 + p2).equals(l1 = p1); + Runnable r = (p2 + p2)::length; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } } - void superCall(@Odd String p1, String p2) { + void superMethodReference(@Odd String p1, String p2) { String l1 = p1; try { mayThrow(); l1 = p2; - super.equals(l1 = p1); + Runnable r = super::hashCode; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } @@ -140,7 +144,8 @@ void lambda(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - ((Runnable) () -> {}).equals(l1 = p1); + Runnable r = ((Runnable) () -> {})::run; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } @@ -151,7 +156,8 @@ void methodReference(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - ((Runnable) this::mayThrow).equals(l1 = p1); + Runnable r = ((Runnable) this::mayThrow)::run; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } @@ -185,7 +191,8 @@ void classLiteral(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - String.class.equals(l1 = p1); + Runnable r = String.class::getName; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } @@ -200,7 +207,8 @@ void enumConstant(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - Color.RED.equals(l1 = p1); + Runnable r = Color.RED::name; + l1 = p1; } catch (NullPointerException e) { // An enum constant is null if it is read during class initialization before it is assigned. // :: error: [assignment] @@ -215,7 +223,8 @@ void enumFieldMayBeNull(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - favoriteColor.equals(l1 = p1); + Runnable r = favoriteColor::name; + l1 = p1; } catch (NullPointerException e) { // :: error: [assignment] @Odd String l3 = l1; @@ -227,11 +236,13 @@ void switchExpression(@Odd String p1, String p2, int i) { try { mayThrow(); l1 = p2; - (switch (i) { - case 1 -> "a"; - default -> "b"; - }) - .equals(l1 = p1); + Runnable r = + (switch (i) { + case 1 -> "a"; + default -> "b"; + }) + ::length; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } @@ -242,17 +253,34 @@ void switchExpressionMayBeNull(@Odd String p1, String p2, int i, String s) { try { mayThrow(); l1 = p2; - (switch (i) { - case 1 -> "a"; - default -> s; - }) - .equals(l1 = p1); + Runnable r = + (switch (i) { + case 1 -> "a"; + default -> s; + }) + ::length; + l1 = p1; } catch (NullPointerException e) { // :: error: [assignment] @Odd String l3 = l1; } } + void methodReferenceMayBeNull(@Odd String p1, String p2, String s) { + String l1 = p1; + try { + mayThrow(); + l1 = p2; + Runnable r = s::length; + l1 = p1; + } catch (NullPointerException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } + + // A call tests its receiver for nullness only after evaluating its arguments (JLS 15.12.4.4), so + // `l1` is p1 when a null receiver causes a NullPointerException. void methodCallMayBeNull(@Odd String p1, String p2, String s) { String l1 = p1; try { @@ -260,7 +288,6 @@ void methodCallMayBeNull(@Odd String p1, String p2, String s) { l1 = p2; s.equals(l1 = p1); } catch (NullPointerException e) { - // :: error: [assignment] @Odd String l3 = l1; } } @@ -271,7 +298,8 @@ void qualifiedThis(@Odd String p1, String p2) { try { mayThrow(); l1 = p2; - ReceiverNullPointerException.this.equals(l1 = p1); + Runnable r = ReceiverNullPointerException.this::hashCode; + l1 = p1; } catch (NullPointerException e) { @Odd String l3 = l1; } From 47bba23a4a784f0f9c2263dfd1947feb1d25b1b6 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 12 Nov 2026 11:44:53 -0800 Subject: [PATCH 07/98] Refine a call's receiver to non-null only after the call completes normally A call tests its receiver for nullness only after evaluating its arguments, so neither the arguments nor a handler for the call's NullPointerException may assume that the receiver is non-null. Moved from #8397. --- .../checker/nullness/NullnessTransfer.java | 17 ++++---------- .../nullness/ReceiverRefinementInCatch.java | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+), 13 deletions(-) create mode 100644 checker/tests/nullness/ReceiverRefinementInCatch.java diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 148b72addf16..185310bbd1c4 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -22,7 +22,6 @@ import org.checkerframework.dataflow.cfg.node.ArrayAccessNode; import org.checkerframework.dataflow.cfg.node.FieldAccessNode; import org.checkerframework.dataflow.cfg.node.InstanceOfNode; -import org.checkerframework.dataflow.cfg.node.MethodAccessNode; import org.checkerframework.dataflow.cfg.node.MethodInvocationNode; import org.checkerframework.dataflow.cfg.node.Node; import org.checkerframework.dataflow.cfg.node.NullLiteralNode; @@ -362,18 +361,6 @@ public TransferResult visitInstanceOf( return new ConditionalTransferResult<>(result.getResultValue(), thenStore, elseStore); } - @Override - public TransferResult visitMethodAccess( - MethodAccessNode n, TransferInput p) { - TransferResult result = super.visitMethodAccess(n, p); - // The receiver of an instance method access is non-null. A static method access does not - // ensure that the receiver is non-null. - if (!n.isStatic()) { - makeNonNull(result, n.getReceiver()); - } - return result; - } - @Override public TransferResult visitFieldAccess( FieldAccessNode n, TransferInput p) { @@ -427,6 +414,10 @@ public TransferResult visitMethodInvocation( atypeFactory.isSideEffectFree(method) || PurityUtils.isSideEffectFree(atypeFactory, method); Node receiver = n.getTarget().getReceiver(); // A static method invocation does not dereference its receiver. + // The receiver is refined here, after the invocation completes normally, rather than at the + // MethodAccessNode. A call tests its receiver for nullness after evaluating its arguments, so + // neither the arguments nor a handler for the call's NullPointerException may assume that the + // receiver is non-null. if (!n.getTarget().isStatic() && (nonNullAssumptionAfterInvocation || isMethodSideEffectFree diff --git a/checker/tests/nullness/ReceiverRefinementInCatch.java b/checker/tests/nullness/ReceiverRefinementInCatch.java new file mode 100644 index 000000000000..656815da2635 --- /dev/null +++ b/checker/tests/nullness/ReceiverRefinementInCatch.java @@ -0,0 +1,23 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// A call's NullPointerException for a null receiver must not carry a non-null refinement of the +// receiver into a catch block. +public class ReceiverRefinementInCatch { + + void m(@Nullable Object o) { + try { + // :: error: (dereference.of.nullable) + o.toString(); + } catch (NullPointerException e) { + // :: error: (dereference.of.nullable) + o.hashCode(); + } + } + + void afterNormalCompletion(@Nullable Object o) { + // :: error: (dereference.of.nullable) + o.toString(); + // The call completed normally, so o is non-null. + o.hashCode(); + } +} From c62d7209c2882bdc4452fecfc99d8519e824ca81 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 21:05:22 -0800 Subject: [PATCH 08/98] Give enhanced-for synthetic calls exceptional edges; don't rescan next() Route the synthetic iterator(), hasNext(), and next() calls through extendWithMethodInvocationNode, so that a terminating call still reaches enclosing catch and finally blocks and the Resource Leak Checker sees an exceptional edge rather than a normal one. Pass nextCallNode, not the next() tree, to translateAssignment, so that next() appears once in the CFG. --- .../resourceleak/TerminatingEnhancedFor.java | 24 ++++++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 32 +++---------------- framework/tests/flow/Termination.java | 15 +++++++++ 3 files changed, 43 insertions(+), 28 deletions(-) create mode 100644 checker/tests/resourceleak/TerminatingEnhancedFor.java diff --git a/checker/tests/resourceleak/TerminatingEnhancedFor.java b/checker/tests/resourceleak/TerminatingEnhancedFor.java new file mode 100644 index 000000000000..04ada36e3547 --- /dev/null +++ b/checker/tests/resourceleak/TerminatingEnhancedFor.java @@ -0,0 +1,24 @@ +// A test that a terminating call that an enhanced for loop desugars to does not cause a false +// positive. + +import java.io.IOException; +import java.net.Socket; +import java.util.Iterator; +import org.checkerframework.dataflow.qual.TerminatesExecution; + +class TerminatingEnhancedFor { + + static class TerminatingIterable implements Iterable { + @Override + @TerminatesExecution + public Iterator iterator() { + throw new Error(); + } + } + + void m(String host, int port, TerminatingIterable it) throws IOException { + Socket s = new Socket(host, port); + for (String x : it) {} + s.close(); + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 9beb6d198b69..3bb598eb321c 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1781,7 +1781,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - extendWithSyntheticMethodInvocationNode(iteratorCallNode); + extendWithMethodInvocationNode(iteratorCallNode.getTarget().getMethod(), iteratorCallNode); translateAssignment( iteratorVariable, new LocalVariableNode(iteratorVariable), iteratorCallNode); @@ -1810,7 +1810,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( hasNextCall, hasNextAccessNode, Collections.emptyList(), getCurrentPath()); hasNextCallNode.setInSource(false); - extendWithSyntheticMethodInvocationNode(hasNextCallNode); + extendWithMethodInvocationNode(hasNextCallNode.getTarget().getMethod(), hasNextCallNode); extendWithExtendedNode(new ConditionalJump(loopEntry, loopExit)); // Loop body, starting with declaration of the loop iteration variable @@ -1843,14 +1843,9 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { nextCallNode.setIterableExpression(expression); nextCallNode.setEnhancedForLoop(tree); nextCallNode.setInSource(false); - extendWithSyntheticMethodInvocationNode(nextCallNode); + extendWithMethodInvocationNode(nextCallNode.getTarget().getMethod(), nextCallNode); - AssignmentNode assignNode = - translateAssignment(variable, new LocalVariableNode(variable), nextCall); - // translateAssignment() scans variable and creates new nodes, so set the expression - // there, too. - ((MethodInvocationNode) assignNode.getExpression()).setIterableExpression(expression); - ((MethodInvocationNode) assignNode.getExpression()).setEnhancedForLoop(tree); + translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); assert statement != null; scan(statement, p); @@ -3402,25 +3397,6 @@ private ExtendedNode extendWithMethodInvocationNode( return extendedNode; } - /** - * Extends the CFG with a MethodInvocationNode for a call that the CFG builder synthesizes, such - * as the calls to {@code iterator()}, {@code hasNext()}, and {@code next()} in an enhanced for - * loop. Unlike {@link #extendWithMethodInvocationNode}, does not add exceptional edges. If the - * method is annotated {@link TerminatesExecution}, the invocation terminates execution. - * - * @param node the invocation - */ - private void extendWithSyntheticMethodInvocationNode(MethodInvocationNode node) { - addToLookupMap(node); - NodeHolder holder = new NodeHolder(node); - if (annotationProvider.getDeclAnnotation( - node.getTarget().getMethod(), TerminatesExecution.class) - != null) { - holder.setTerminatesExecution(true); - } - extendWithExtendedNode(holder); - } - @Override public Node visitNewClass(NewClassTree tree, Void p) { // see JLS 15.9 diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index e0e164184c89..9124e2f3e31c 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -85,4 +85,19 @@ void t6(@Odd String p1, String p2, boolean b1, TerminatingIterable it) { } @Odd String l3 = l1; } + + // The desugared call to iterator() can throw an exception that a catch clause handles. + void t7(@Odd String p1, String p2, boolean b1, TerminatingIterable it) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try { + for (String s : it) {} + } catch (Error e) { + } + } + // :: error: [assignment] + @Odd String l3 = l1; + } } From c4bb41d3ed8bb7f08e3c68d25d25e579360827a3 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 22:31:04 -0800 Subject: [PATCH 09/98] Make extendWithMethodInvocationNode void and derive the method from the node --- .../cfg/builder/CFGTranslationPhaseOne.java | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 3bb598eb321c..1ec7c3533d8d 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1781,7 +1781,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - extendWithMethodInvocationNode(iteratorCallNode.getTarget().getMethod(), iteratorCallNode); + extendWithMethodInvocationNode(iteratorCallNode); translateAssignment( iteratorVariable, new LocalVariableNode(iteratorVariable), iteratorCallNode); @@ -1810,7 +1810,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( hasNextCall, hasNextAccessNode, Collections.emptyList(), getCurrentPath()); hasNextCallNode.setInSource(false); - extendWithMethodInvocationNode(hasNextCallNode.getTarget().getMethod(), hasNextCallNode); + extendWithMethodInvocationNode(hasNextCallNode); extendWithExtendedNode(new ConditionalJump(loopEntry, loopExit)); // Loop body, starting with declaration of the loop iteration variable @@ -1843,7 +1843,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { nextCallNode.setIterableExpression(expression); nextCallNode.setEnhancedForLoop(tree); nextCallNode.setInSource(false); - extendWithMethodInvocationNode(nextCallNode.getTarget().getMethod(), nextCallNode); + extendWithMethodInvocationNode(nextCallNode); translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); @@ -2740,7 +2740,7 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { new MethodInvocationNode( closeCall, closeAccessNode, Collections.emptyList(), getCurrentPath()); closeCallNode.setInSource(false); - extendWithMethodInvocationNode(TreeUtils.elementFromUse(closeCall), closeCallNode); + extendWithMethodInvocationNode(closeCallNode); if (resourceMayBeNull) { addLabelForNextNode(afterCloseLabel); @@ -3367,21 +3367,19 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi MethodInvocationNode node = new MethodInvocationNode(tree, target, arguments, getCurrentPath()); - extendWithMethodInvocationNode(method, node); + extendWithMethodInvocationNode(node); return node; } /** - * Extends the CFG with a MethodInvocationNode, accounting for potential exceptions thrown by the - * invocation. If the method is annotated {@link TerminatesExecution}, the invocation terminates - * execution. + * Extends the CFG with the given MethodInvocationNode, accounting for potential exceptions thrown + * by the invocation. If the method is annotated {@link TerminatesExecution}, the invocation + * terminates execution. * - * @param method the invoked method - * @param node the invocation - * @return an ExtendedNode representing the invocation and its possible thrown exceptions + * @param node an invocation */ - private ExtendedNode extendWithMethodInvocationNode( - ExecutableElement method, MethodInvocationNode node) { + private void extendWithMethodInvocationNode(MethodInvocationNode node) { + ExecutableElement method = node.getTarget().getMethod(); List thrownTypes = method.getThrownTypes(); Set thrownSet = new LinkedHashSet<>(thrownTypes.size() + uncheckedExceptionTypes.size()); @@ -3394,7 +3392,6 @@ private ExtendedNode extendWithMethodInvocationNode( if (annotationProvider.getDeclAnnotation(method, TerminatesExecution.class) != null) { extendedNode.setTerminatesExecution(true); } - return extendedNode; } @Override From 2ec36b17410da72b031b2643ddd572e9a15a4fcc Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 14 Nov 2026 20:12:03 -0800 Subject: [PATCH 10/98] RLC: a @PolyMustCall alias has the must-call methods of its fellow aliases The desugared iterator() call of an enhanced for loop now has exceptional edges. At a handler that both the iterator() call and the loop body reach, the Must Call store has no refined type for the loop's iterator variable, whose declared type is @PolyMustCall when iterator() returns @MustCallAlias. That made the obligation unsatisfiable and caused a false positive required.method.not.known error (seen in plume-lib/multi-version-control). --- .../MustCallConsistencyAnalyzer.java | 20 +++++ .../MustCallAliasEnhancedFor.java | 74 +++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 checker/tests/resourceleak/MustCallAliasEnhancedFor.java diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 2940838442a1..6359d276a38b 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -337,8 +337,18 @@ public boolean derivedFromMustCallAlias() { MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); + // The aliases whose must-call type is @PolyMustCall. Such an alias is the result of a + // @MustCallAlias method, such as the iterator variable of an enhanced for loop whose + // iterator() method returns @MustCallAlias, and the store contains no refined type for it. + // It has the same must-call methods as the other aliases. + List polyAliases = new ArrayList<>(0); + List nonPolyAnnoVals = null; for (ResourceAlias alias : this.resourceAliases) { AnnotationMirror mcAnno = getMustCallValue(alias, mcStore, mustCallAnnotatedTypeFactory); + if (AnnotationUtils.areSame(mcAnno, mustCallAnnotatedTypeFactory.POLY)) { + polyAliases.add(alias); + continue; + } if (!AnnotationUtils.areSameByName(mcAnno, MustCall.class.getCanonicalName())) { // MustCallUnknown; cannot be satisfied return null; @@ -348,6 +358,16 @@ public boolean derivedFromMustCallAlias() { // obligation in the first place. // TODO: add an assertion that annoVals is non-empty and address any failures result.put(alias, annoVals); + nonPolyAnnoVals = annoVals; + } + if (!polyAliases.isEmpty()) { + if (nonPolyAnnoVals == null) { + // No alias has a known must-call type; cannot be satisfied + return null; + } + for (ResourceAlias alias : polyAliases) { + result.put(alias, nonPolyAnnoVals); + } } return result; } diff --git a/checker/tests/resourceleak/MustCallAliasEnhancedFor.java b/checker/tests/resourceleak/MustCallAliasEnhancedFor.java new file mode 100644 index 000000000000..418c58356c1e --- /dev/null +++ b/checker/tests/resourceleak/MustCallAliasEnhancedFor.java @@ -0,0 +1,74 @@ +// A test of an enhanced for loop over a resource whose iterator() method returns @MustCallAlias. +// The loop's desugared iterator() call might throw an exception before the loop's iterator +// variable is assigned, so the store at a handler that the loop body's exceptions also reach has +// no refined type for the iterator variable. + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.Iterator; +import org.checkerframework.checker.mustcall.qual.MustCallAlias; + +class MustCallAliasEnhancedFor { + + static class LineReader extends BufferedReader implements Iterable, Iterator { + @MustCallAlias LineReader(@MustCallAlias Reader in) { + super(in); + } + + LineReader(String filename) throws IOException { + this(new FileReader(filename)); + } + + @Override + @SuppressWarnings("mustcall:override.return") + public @MustCallAlias Iterator iterator(@MustCallAlias LineReader this) { + return this; + } + + @Override + public boolean hasNext() { + return false; + } + + @Override + public String next() { + throw new Error(); + } + } + + static void process(String s) throws IOException {} + + void tryWithResources(String filename) throws IOException { + try (LineReader lr = new LineReader(filename)) { + for (String line : lr) { + process(line); + } + } + } + + void closeInFinally(String filename) throws IOException { + LineReader lr = new LineReader(filename); + try { + for (String line : lr) { + process(line); + } + } finally { + lr.close(); + } + } + + void leakInCatch(String filename) throws IOException { + // :: error: (required.method.not.called) + LineReader lr = new LineReader(filename); + try { + for (String line : lr) { + process(line); + } + } catch (IOException e) { + return; + } + lr.close(); + } +} From 39380a3c6b820b6408182c55f4b1601bb1ad0c61 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 14 Nov 2026 20:30:20 -0800 Subject: [PATCH 11/98] RLC: an unrefined alias has the must-call methods of a refined alias All the resource aliases of an Obligation refer to the same resource. A resource alias that has no @MustCall type in the Must Call store -- for example, because it is unassigned on some path to the store's program point -- now takes the must-call methods of a resource alias that has one, rather than falling back to its declared type or its class's default. This generalizes the previous @PolyMustCall special case, and it also reports the leak in #8578, where an explicit Iterator variable fell back to the Iterator class's empty must-call type. --- .../MustCallConsistencyAnalyzer.java | 80 +++++++++++-------- ...cedFor.java => MustCallAliasIterator.java} | 49 ++++++++++-- 2 files changed, 90 insertions(+), 39 deletions(-) rename checker/tests/resourceleak/{MustCallAliasEnhancedFor.java => MustCallAliasIterator.java} (53%) diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 6359d276a38b..1d035f403437 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -324,12 +324,19 @@ public boolean derivedFromMustCallAlias() { * Gets the must-call methods (i.e., the list of methods that must be called to satisfy the * must-call obligation) of each resource alias represented by this Obligation. * + *

All the resource aliases of an Obligation refer to the same resource. Therefore, a + * resource alias that has no {@code @MustCall} type in the store has the must-call methods of a + * resource alias that does. For example, the store lacks a resource alias that is unassigned on + * some path to the store's program point, such as a variable that is assigned the result of a + * {@code @MustCallAlias} method that might throw an exception. + * * @param rlAtf a Resource Leak Annotated Type Factory * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis. If this is * null, then the default MustCall type of each variable's class will be used. * @return a map from each resource alias of this to a list of its must-call method names, or - * null if the must-call obligations are unsatisfiable (i.e., the value of some tracked - * resource alias of this in the Must Call store is MustCallUnknown) + * null if the must-call obligations are unsatisfiable (i.e., no resource alias of this has + * a {@code @MustCall} type in the Must Call store, and the declared type of some resource + * alias of this is not a {@code @MustCall} type, such as MustCallUnknown) */ public @Nullable Map> getMustCallMethods( RLCCalledMethodsAnnotatedTypeFactory rlAtf, @Nullable CFStore mcStore) { @@ -337,18 +344,26 @@ public boolean derivedFromMustCallAlias() { MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); - // The aliases whose must-call type is @PolyMustCall. Such an alias is the result of a - // @MustCallAlias method, such as the iterator variable of an enhanced for loop whose - // iterator() method returns @MustCallAlias, and the store contains no refined type for it. - // It has the same must-call methods as the other aliases. - List polyAliases = new ArrayList<>(0); - List nonPolyAnnoVals = null; + // The resource aliases that have no @MustCall type in the store. + List unrefinedAliases = new ArrayList<>(0); + // The must-call methods of a resource alias that has a @MustCall type in the store. + List refinedAnnoVals = null; for (ResourceAlias alias : this.resourceAliases) { - AnnotationMirror mcAnno = getMustCallValue(alias, mcStore, mustCallAnnotatedTypeFactory); - if (AnnotationUtils.areSame(mcAnno, mustCallAnnotatedTypeFactory.POLY)) { - polyAliases.add(alias); + AnnotationMirror mcAnno = getRefinedMustCallValue(alias, mcStore); + if (mcAnno == null) { + unrefinedAliases.add(alias); + continue; + } + refinedAnnoVals = rlAtf.getMustCallValues(mcAnno); + result.put(alias, refinedAnnoVals); + } + + for (ResourceAlias alias : unrefinedAliases) { + if (refinedAnnoVals != null) { + result.put(alias, refinedAnnoVals); continue; } + AnnotationMirror mcAnno = getMustCallValue(alias, mustCallAnnotatedTypeFactory); if (!AnnotationUtils.areSameByName(mcAnno, MustCall.class.getCanonicalName())) { // MustCallUnknown; cannot be satisfied return null; @@ -358,41 +373,37 @@ public boolean derivedFromMustCallAlias() { // obligation in the first place. // TODO: add an assertion that annoVals is non-empty and address any failures result.put(alias, annoVals); - nonPolyAnnoVals = annoVals; - } - if (!polyAliases.isEmpty()) { - if (nonPolyAnnoVals == null) { - // No alias has a known must-call type; cannot be satisfied - return null; - } - for (ResourceAlias alias : polyAliases) { - result.put(alias, nonPolyAnnoVals); - } } return result; } /** - * Gets the must-call type associated with the given resource alias, falling back on the - * declared type if there is no refined type for the alias in the store. + * Returns the {@code @MustCall} type of the given resource alias in the given store. * * @param alias a resource alias * @param mcStore the must-call checker's store + * @return the {@code @MustCall} annotation of {@code alias} in {@code mcStore}, or null if + * {@code mcStore} is null or has no {@code @MustCall} type for {@code alias} + */ + private static @Nullable AnnotationMirror getRefinedMustCallValue( + ResourceAlias alias, @Nullable CFStore mcStore) { + CFValue value = mcStore == null ? null : mcStore.getValue(alias.reference); + if (value == null) { + return null; + } + return AnnotationUtils.getAnnotationByClass(value.getAnnotations(), MustCall.class); + } + + /** + * Returns the must-call type of the given resource alias, ignoring any store: its declared + * type, or the default must-call type of its class if its declared type is top. + * + * @param alias a resource alias * @param mcAtf the must-call checker's annotated type factory * @return the annotation from the must-call type hierarchy associated with {@code alias} */ private static AnnotationMirror getMustCallValue( - ResourceAlias alias, @Nullable CFStore mcStore, MustCallAnnotatedTypeFactory mcAtf) { - JavaExpression reference = alias.reference; - CFValue value = mcStore == null ? null : mcStore.getValue(reference); - if (value != null) { - AnnotationMirror result = - AnnotationUtils.getAnnotationByClass(value.getAnnotations(), MustCall.class); - if (result != null) { - return result; - } - } - + ResourceAlias alias, MustCallAnnotatedTypeFactory mcAtf) { AnnotationMirror result = mcAtf.getAnnotatedType(alias.element).getAnnotationInHierarchy(mcAtf.TOP); if (result != null && !AnnotationUtils.areSame(result, mcAtf.TOP)) { @@ -403,6 +414,7 @@ private static AnnotationMirror getMustCallValue( // TODO: we currently end up in this case when checking a call to the return type // of a returns-receiver method on something with a MustCall type; for example, // see tests/socket/ZookeeperReport6.java. We should instead use a poly type if we can. + JavaExpression reference = alias.reference; TypeElement typeElt = TypesUtils.getTypeElement(reference.getType()); if (typeElt == null) { // typeElt is null if reference.getType() was not a class, interface, annotation diff --git a/checker/tests/resourceleak/MustCallAliasEnhancedFor.java b/checker/tests/resourceleak/MustCallAliasIterator.java similarity index 53% rename from checker/tests/resourceleak/MustCallAliasEnhancedFor.java rename to checker/tests/resourceleak/MustCallAliasIterator.java index 418c58356c1e..e25f723c10a0 100644 --- a/checker/tests/resourceleak/MustCallAliasEnhancedFor.java +++ b/checker/tests/resourceleak/MustCallAliasIterator.java @@ -1,7 +1,7 @@ -// A test of an enhanced for loop over a resource whose iterator() method returns @MustCallAlias. -// The loop's desugared iterator() call might throw an exception before the loop's iterator -// variable is assigned, so the store at a handler that the loop body's exceptions also reach has -// no refined type for the iterator variable. +// A test of iteration over a resource whose iterator() method returns @MustCallAlias. The +// iterator() call might throw an exception before the iterator variable is assigned, so the store +// at a handler that the loop body's exceptions also reach has no refined type for the iterator +// variable. The iterator variable is a resource alias of the resource. import java.io.BufferedReader; import java.io.FileReader; @@ -10,7 +10,7 @@ import java.util.Iterator; import org.checkerframework.checker.mustcall.qual.MustCallAlias; -class MustCallAliasEnhancedFor { +class MustCallAliasIterator { static class LineReader extends BufferedReader implements Iterable, Iterator { @MustCallAlias LineReader(@MustCallAlias Reader in) { @@ -71,4 +71,43 @@ void leakInCatch(String filename) throws IOException { } lr.close(); } + + void leakInCatchException(String filename) throws IOException { + // :: error: (required.method.not.called) + LineReader lr = new LineReader(filename); + try { + for (String line : lr) { + process(line); + } + } catch (Exception e) { + return; + } + lr.close(); + } + + // Test case for https://github.com/typetools/checker-framework/issues/8578 . + void leakExplicitIterator(String filename) throws IOException { + // :: error: (required.method.not.called) + LineReader lr = new LineReader(filename); + try { + Iterator it = lr.iterator(); + while (it.hasNext()) { + process(it.next()); + } + } catch (Exception e) { + return; + } + lr.close(); + } + + void leakNoIterator(String filename) throws IOException { + // :: error: (required.method.not.called) + LineReader lr = new LineReader(filename); + try { + process(lr.readLine()); + } catch (Exception e) { + return; + } + lr.close(); + } } From 9c5a442b4ed2639a1f334c289674578ae010106e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 14 Nov 2026 20:46:59 -0800 Subject: [PATCH 12/98] Address review: unboxing node, array-branch comment, Javadoc, tests * Give the unboxing conversion of an enhanced for loop's next() call the iterable expression, as the array branch does for its conversion. * In the array branch, drop the redundant re-set of the ArrayAccessNode and correct the comment about translateAssignment(). * Document all the results of getMustCallValue. * Justify a warning suppression in MustCallAliasIterator. * TerminatingEnhancedFor: add a case that fails without the change. --- .../MustCallConsistencyAnalyzer.java | 9 +++++--- .../resourceleak/MustCallAliasIterator.java | 2 +- .../resourceleak/TerminatingEnhancedFor.java | 11 +++++++-- .../cfg/builder/CFGTranslationPhaseOne.java | 23 +++++++++++-------- 4 files changed, 29 insertions(+), 16 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 1d035f403437..bf47478c9406 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -332,7 +332,8 @@ public boolean derivedFromMustCallAlias() { * * @param rlAtf a Resource Leak Annotated Type Factory * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis. If this is - * null, then the default MustCall type of each variable's class will be used. + * null, then the must-call type of each resource alias is computed as by {@link + * #getMustCallValue}, from its declared type or its class. * @return a map from each resource alias of this to a list of its must-call method names, or * null if the must-call obligations are unsatisfiable (i.e., no resource alias of this has * a {@code @MustCall} type in the Must Call store, and the declared type of some resource @@ -395,8 +396,10 @@ public boolean derivedFromMustCallAlias() { } /** - * Returns the must-call type of the given resource alias, ignoring any store: its declared - * type, or the default must-call type of its class if its declared type is top. + * Returns the must-call type of the given resource alias, ignoring any store. That is its + * declared type, unless its declared type is top. In that case, it is the default must-call + * type of the alias's class; or top if the alias's type is not a class, interface, annotation + * type, or enum (for example, if it is a wildcard type); or bottom if the alias's type is void. * * @param alias a resource alias * @param mcAtf the must-call checker's annotated type factory diff --git a/checker/tests/resourceleak/MustCallAliasIterator.java b/checker/tests/resourceleak/MustCallAliasIterator.java index e25f723c10a0..c285dec49bea 100644 --- a/checker/tests/resourceleak/MustCallAliasIterator.java +++ b/checker/tests/resourceleak/MustCallAliasIterator.java @@ -22,7 +22,7 @@ static class LineReader extends BufferedReader implements Iterable, Iter } @Override - @SuppressWarnings("mustcall:override.return") + @SuppressWarnings("mustcall:override.return") // the iterator is this, which must be closed public @MustCallAlias Iterator iterator(@MustCallAlias LineReader this) { return this; } diff --git a/checker/tests/resourceleak/TerminatingEnhancedFor.java b/checker/tests/resourceleak/TerminatingEnhancedFor.java index 04ada36e3547..72186702bae7 100644 --- a/checker/tests/resourceleak/TerminatingEnhancedFor.java +++ b/checker/tests/resourceleak/TerminatingEnhancedFor.java @@ -1,5 +1,5 @@ -// A test that a terminating call that an enhanced for loop desugars to does not cause a false -// positive. +// A test that the Resource Leak Checker honors @TerminatesExecution on a call that an enhanced for +// loop desugars to. import java.io.IOException; import java.net.Socket; @@ -21,4 +21,11 @@ void m(String host, int port, TerminatingIterable it) throws IOException { for (String x : it) {} s.close(); } + + // The loop's iterator() call terminates execution, so no code after the loop executes, and the + // socket need not be closed. + void noCloseAfterLoop(String host, int port, TerminatingIterable it) throws IOException { + Socket s = new Socket(host, port); + for (String x : it) {} + } } diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index b7087c6bbf72..0b74927009fc 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1852,7 +1852,15 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { nextCallNode.setInSource(false); extendWithMethodInvocationNode(nextCallNode); - translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); + AssignmentNode assignNode = + translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); + // If the loop variable is a primitive, the assignment's expression is the unboxing + // conversion of nextCallNode. Save the expression in that node, too. + if (assignNode.getExpression() instanceof MethodInvocationNode unboxingNode + && unboxingNode != nextCallNode) { + unboxingNode.setIterableExpression(expression); + unboxingNode.setEnhancedForLoop(tree); + } assert statement != null; scan(statement, p); @@ -1947,15 +1955,10 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { extendWithNode(arrayAccessNode); AssignmentNode arrayAccessAssignNode = translateAssignment(variable, new LocalVariableNode(variable), arrayAccessNode); - // translateAssignment() scans variable and creates new nodes, so set the expression - // there, too. - Node arrayAccessAssignNodeExpr = arrayAccessAssignNode.getExpression(); - if (arrayAccessAssignNodeExpr instanceof ArrayAccessNode aan) { - aan.setArrayExpression(expression); - aan.setEnhancedForLoop(tree); - } else if (arrayAccessAssignNodeExpr instanceof MethodInvocationNode boxingNode) { - // If the array component type is a primitive, there may be a boxing or unboxing - // conversion. Treat that as an iterator. + // If the loop variable's type and the array's component type differ by a boxing or + // unboxing conversion, the assignment's expression is the conversion of arrayAccessNode. + // Treat that conversion as an iterator. + if (arrayAccessAssignNode.getExpression() instanceof MethodInvocationNode boxingNode) { boxingNode.setIterableExpression(expression); boxingNode.setEnhancedForLoop(tree); } From a4943f76fffebd1a7f06bec0d76945393ecc1420 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 14 Nov 2026 21:26:50 -0800 Subject: [PATCH 13/98] Unwrap widening to find an enhanced-for element's boxing conversion; fix comments --- .../MustCallConsistencyAnalyzer.java | 3 +- .../cfg/builder/CFGTranslationPhaseOne.java | 44 +++++++++++++++---- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index bf47478c9406..1995239ad144 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -412,8 +412,7 @@ private static AnnotationMirror getMustCallValue( if (result != null && !AnnotationUtils.areSame(result, mcAtf.TOP)) { return result; } - // There wasn't an @MustCall annotation for it in the store and the type factory has no - // information, so fall back to the default must-call type for the class. + // The declared type is top, so fall back to the default must-call type for the class. // TODO: we currently end up in this case when checking a call to the return type // of a returns-receiver method on something with a MustCall type; for example, // see tests/socket/ZookeeperReport6.java. We should instead use a poly type if we can. diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 0b74927009fc..a0f0c8fc342f 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1854,10 +1854,11 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { AssignmentNode assignNode = translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); - // If the loop variable is a primitive, the assignment's expression is the unboxing - // conversion of nextCallNode. Save the expression in that node, too. - if (assignNode.getExpression() instanceof MethodInvocationNode unboxingNode - && unboxingNode != nextCallNode) { + // If the loop variable is a primitive, the assignment unboxes the result of next(). Save + // the iterable expression in the unboxing conversion, too. + MethodInvocationNode unboxingNode = + getBoxingConversion(assignNode.getExpression(), nextCallNode); + if (unboxingNode != null) { unboxingNode.setIterableExpression(expression); unboxingNode.setEnhancedForLoop(tree); } @@ -1956,9 +1957,10 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { AssignmentNode arrayAccessAssignNode = translateAssignment(variable, new LocalVariableNode(variable), arrayAccessNode); // If the loop variable's type and the array's component type differ by a boxing or - // unboxing conversion, the assignment's expression is the conversion of arrayAccessNode. - // Treat that conversion as an iterator. - if (arrayAccessAssignNode.getExpression() instanceof MethodInvocationNode boxingNode) { + // unboxing conversion, treat that conversion as an iterator. + MethodInvocationNode boxingNode = + getBoxingConversion(arrayAccessAssignNode.getExpression(), arrayAccessNode); + if (boxingNode != null) { boxingNode.setIterableExpression(expression); boxingNode.setEnhancedForLoop(tree); } @@ -2019,6 +2021,30 @@ protected VariableTree createEnhancedForLoopIteratorVariable( return iteratorVariable; } + /** + * Returns the boxing or unboxing conversion of the given enhanced for loop element, within the + * expression that is assigned to the loop variable. For example, if {@code list} is a {@code + * List}, then in {@code for (long x : list)}, the expression that is assigned to {@code + * x} widens the unboxing conversion of the result of {@code next()}. + * + * @param assignedExpression the expression assigned to an enhanced for loop's variable + * @param element the loop's element, before any conversion: a call to {@code next()} or an array + * access + * @return the boxing or unboxing conversion of {@code element} in {@code assignedExpression}, or + * null if there is none + */ + private static @Nullable MethodInvocationNode getBoxingConversion( + Node assignedExpression, Node element) { + Node unwidened = + assignedExpression instanceof WideningConversionNode widening + ? widening.getOperand() + : assignedExpression; + if (unwidened != element && unwidened instanceof MethodInvocationNode result) { + return result; + } + return null; + } + protected VariableTree createEnhancedForLoopArrayVariable( ExpressionTree expression, VariableElement variableElement) { TypeMirror arrayType = TreeUtils.typeOf(expression); @@ -3383,8 +3409,8 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi /** * Extends the CFG with the given MethodInvocationNode, accounting for potential exceptions thrown - * by the invocation. If the method is annotated {@link TerminatesExecution}, the invocation - * terminates execution. + * by the invocation. If the invoked method (the method of {@code node}'s target) is annotated + * {@link TerminatesExecution}, the invocation terminates execution. * * @param node an invocation */ From 62e326e420e1a13388fd96fe7dd3329be62707e0 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 10:34:37 -0800 Subject: [PATCH 14/98] RLC: an alias that has no @MustCall type in the store cannot satisfy an Obligation Omit such an alias from the result of Obligation.getMustCallMethods, rather than giving it the must-call methods of an arbitrary other alias. Rename "refined" to "from store", and getMustCallValue to getMustCallValueFromDeclaration. --- .../MustCallConsistencyAnalyzer.java | 84 +++++++++---------- .../resourceleak/MustCallAliasIterator.java | 2 +- 2 files changed, 43 insertions(+), 43 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 1995239ad144..973563a404c7 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -16,7 +16,6 @@ import java.util.Collections; import java.util.Deque; import java.util.EnumSet; -import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; @@ -321,50 +320,50 @@ public boolean derivedFromMustCallAlias() { } /** - * Gets the must-call methods (i.e., the list of methods that must be called to satisfy the - * must-call obligation) of each resource alias represented by this Obligation. + * Returns the must-call methods (i.e., the list of methods that must be called to satisfy the + * must-call obligation) of each resource alias of this Obligation through which the obligation + * can be satisfied. * - *

All the resource aliases of an Obligation refer to the same resource. Therefore, a - * resource alias that has no {@code @MustCall} type in the store has the must-call methods of a - * resource alias that does. For example, the store lacks a resource alias that is unassigned on - * some path to the store's program point, such as a variable that is assigned the result of a - * {@code @MustCallAlias} method that might throw an exception. + *

If some resource alias of this has a {@code @MustCall} type in the store, then the result + * contains exactly the resource aliases that have one. A resource alias that has no + * {@code @MustCall} type in the store cannot satisfy the obligation, so the result omits it. + * For example, the store lacks a resource alias that is unassigned on some path to the store's + * program point, such as a variable that is assigned the result of a {@code @MustCallAlias} + * method that might throw an exception. The Called Methods store lacks such a resource alias as + * well, so no method is known to have been called on it. Its declared type, however, might be + * {@code @MustCall({})}, as for a variable of type {@code Iterator}; using that type would make + * the obligation trivially satisfied. + * + *

If no resource alias of this has a {@code @MustCall} type in the store, then the result + * contains every resource alias of this, with the must-call type computed by {@link + * #getMustCallValueFromDeclaration}. * * @param rlAtf a Resource Leak Annotated Type Factory - * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis. If this is - * null, then the must-call type of each resource alias is computed as by {@link - * #getMustCallValue}, from its declared type or its class. - * @return a map from each resource alias of this to a list of its must-call method names, or - * null if the must-call obligations are unsatisfiable (i.e., no resource alias of this has - * a {@code @MustCall} type in the Must Call store, and the declared type of some resource - * alias of this is not a {@code @MustCall} type, such as MustCallUnknown) + * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis, or null + * @return a map from resource aliases of this to lists of their must-call method names, whose + * iteration order is that of {@link #resourceAliases}; or null if the must-call obligations + * are unsatisfiable (i.e., no resource alias of this has a {@code @MustCall} type in the + * Must Call store, and the declared type of some resource alias of this is not a + * {@code @MustCall} type, such as MustCallUnknown) */ public @Nullable Map> getMustCallMethods( RLCCalledMethodsAnnotatedTypeFactory rlAtf, @Nullable CFStore mcStore) { - Map> result = new HashMap<>(this.resourceAliases.size()); - MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = - rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); - - // The resource aliases that have no @MustCall type in the store. - List unrefinedAliases = new ArrayList<>(0); - // The must-call methods of a resource alias that has a @MustCall type in the store. - List refinedAnnoVals = null; + Map> result = new LinkedHashMap<>(this.resourceAliases.size()); for (ResourceAlias alias : this.resourceAliases) { - AnnotationMirror mcAnno = getRefinedMustCallValue(alias, mcStore); - if (mcAnno == null) { - unrefinedAliases.add(alias); - continue; + AnnotationMirror mcAnno = getMustCallValueFromStore(alias, mcStore); + if (mcAnno != null) { + result.put(alias, rlAtf.getMustCallValues(mcAnno)); } - refinedAnnoVals = rlAtf.getMustCallValues(mcAnno); - result.put(alias, refinedAnnoVals); + } + if (!result.isEmpty()) { + return result; } - for (ResourceAlias alias : unrefinedAliases) { - if (refinedAnnoVals != null) { - result.put(alias, refinedAnnoVals); - continue; - } - AnnotationMirror mcAnno = getMustCallValue(alias, mustCallAnnotatedTypeFactory); + MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = + rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); + for (ResourceAlias alias : this.resourceAliases) { + AnnotationMirror mcAnno = + getMustCallValueFromDeclaration(alias, mustCallAnnotatedTypeFactory); if (!AnnotationUtils.areSameByName(mcAnno, MustCall.class.getCanonicalName())) { // MustCallUnknown; cannot be satisfied return null; @@ -386,7 +385,7 @@ public boolean derivedFromMustCallAlias() { * @return the {@code @MustCall} annotation of {@code alias} in {@code mcStore}, or null if * {@code mcStore} is null or has no {@code @MustCall} type for {@code alias} */ - private static @Nullable AnnotationMirror getRefinedMustCallValue( + private static @Nullable AnnotationMirror getMustCallValueFromStore( ResourceAlias alias, @Nullable CFStore mcStore) { CFValue value = mcStore == null ? null : mcStore.getValue(alias.reference); if (value == null) { @@ -405,7 +404,7 @@ public boolean derivedFromMustCallAlias() { * @param mcAtf the must-call checker's annotated type factory * @return the annotation from the must-call type hierarchy associated with {@code alias} */ - private static AnnotationMirror getMustCallValue( + private static AnnotationMirror getMustCallValueFromDeclaration( ResourceAlias alias, MustCallAnnotatedTypeFactory mcAtf) { AnnotationMirror result = mcAtf.getAnnotatedType(alias.element).getAnnotationInHierarchy(mcAtf.TOP); @@ -2393,9 +2392,9 @@ private void checkMustCall( } boolean mustCallSatisfied = false; - for (ResourceAlias alias : obligation.resourceAliases) { - - List mustCallValuesForAlias = mustCallValues.get(alias); + for (Map.Entry> entry : mustCallValues.entrySet()) { + ResourceAlias alias = entry.getKey(); + List mustCallValuesForAlias = entry.getValue(); // optimization when there are no methods to call if (mustCallValuesForAlias.isEmpty()) { mustCallSatisfied = true; @@ -2435,7 +2434,8 @@ private void checkMustCall( if (!mustCallSatisfied) { // Report the error at the first alias' definition. This choice is arbitrary but - // consistent. + // consistent. The first alias might be absent from mustCallValues, so report the + // must-call methods of the first alias that is present. ResourceAlias firstAlias = obligation.resourceAliases.iterator().next(); if (!reportedErrorAliases.contains(firstAlias)) { if (!checker.shouldSkipUses(TreeUtils.elementFromTree(firstAlias.tree))) { @@ -2443,7 +2443,7 @@ private void checkMustCall( checker.reportError( firstAlias.tree, "required.method.not.called", - formatMissingMustCallMethods(mustCallValues.get(firstAlias)), + formatMissingMustCallMethods(mustCallValues.values().iterator().next()), firstAlias.stringForErrorMessage(), firstAlias.reference.getType().toString(), outOfScopeReason); diff --git a/checker/tests/resourceleak/MustCallAliasIterator.java b/checker/tests/resourceleak/MustCallAliasIterator.java index c285dec49bea..1228e3d341a2 100644 --- a/checker/tests/resourceleak/MustCallAliasIterator.java +++ b/checker/tests/resourceleak/MustCallAliasIterator.java @@ -1,6 +1,6 @@ // A test of iteration over a resource whose iterator() method returns @MustCallAlias. The // iterator() call might throw an exception before the iterator variable is assigned, so the store -// at a handler that the loop body's exceptions also reach has no refined type for the iterator +// at a handler that the loop body's exceptions also reach has no @MustCall type for the iterator // variable. The iterator variable is a resource alias of the resource. import java.io.BufferedReader; From 300675f70ad00de629db252d7ce9a18b984dbeda Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 10:35:17 -0800 Subject: [PATCH 15/98] Translate an enhanced for loop's next() once; find the conversion under a widening --- .../cfg/builder/CFGTranslationPhaseOne.java | 54 +++++++++---- .../tests/flow/EnhancedForConversion.java | 75 +++++++++++++++++++ 2 files changed, 114 insertions(+), 15 deletions(-) create mode 100644 framework/tests/flow/EnhancedForConversion.java diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 2370777c9cbd..2d263f881c38 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1850,14 +1850,18 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { nextCallNode.setIterableExpression(expression); nextCallNode.setEnhancedForLoop(tree); nextCallNode.setInSource(false); - extendWithNode(nextCallNode); + extendWithMethodInvocationNode(TreeUtils.elementFromUse(nextCall), nextCallNode); AssignmentNode assignNode = - translateAssignment(variable, new LocalVariableNode(variable), nextCall); - // translateAssignment() scans variable and creates new nodes, so set the expression - // there, too. - ((MethodInvocationNode) assignNode.getExpression()).setIterableExpression(expression); - ((MethodInvocationNode) assignNode.getExpression()).setEnhancedForLoop(tree); + translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); + // If the loop variable is a primitive, the assignment unboxes the result of next(). Save + // the iterable expression in the unboxing conversion, too. + MethodInvocationNode unboxingNode = + getBoxingConversion(assignNode.getExpression(), nextCallNode); + if (unboxingNode != null) { + unboxingNode.setIterableExpression(expression); + unboxingNode.setEnhancedForLoop(tree); + } assert statement != null; scan(statement, p); @@ -1952,15 +1956,11 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { extendWithNode(arrayAccessNode); AssignmentNode arrayAccessAssignNode = translateAssignment(variable, new LocalVariableNode(variable), arrayAccessNode); - // translateAssignment() scans variable and creates new nodes, so set the expression - // there, too. - Node arrayAccessAssignNodeExpr = arrayAccessAssignNode.getExpression(); - if (arrayAccessAssignNodeExpr instanceof ArrayAccessNode aan) { - aan.setArrayExpression(expression); - aan.setEnhancedForLoop(tree); - } else if (arrayAccessAssignNodeExpr instanceof MethodInvocationNode boxingNode) { - // If the array component type is a primitive, there may be a boxing or unboxing - // conversion. Treat that as an iterator. + // If the loop variable's type and the array's component type differ by a boxing or + // unboxing conversion, treat that conversion as an iterator. + MethodInvocationNode boxingNode = + getBoxingConversion(arrayAccessAssignNode.getExpression(), arrayAccessNode); + if (boxingNode != null) { boxingNode.setIterableExpression(expression); boxingNode.setEnhancedForLoop(tree); } @@ -2021,6 +2021,30 @@ protected VariableTree createEnhancedForLoopIteratorVariable( return iteratorVariable; } + /** + * Returns the boxing or unboxing conversion of the given enhanced for loop element, within the + * expression that is assigned to the loop variable. For example, if {@code list} is a {@code + * List}, then in {@code for (long x : list)}, the expression that is assigned to {@code + * x} widens the unboxing conversion of the result of {@code next()}. + * + * @param assignedExpression the expression assigned to an enhanced for loop's variable + * @param element the loop's element, before any conversion: a call to {@code next()} or an array + * access + * @return the boxing or unboxing conversion of {@code element} in {@code assignedExpression}, or + * null if there is none + */ + private static @Nullable MethodInvocationNode getBoxingConversion( + Node assignedExpression, Node element) { + Node unwidened = + assignedExpression instanceof WideningConversionNode widening + ? widening.getOperand() + : assignedExpression; + if (unwidened != element && unwidened instanceof MethodInvocationNode result) { + return result; + } + return null; + } + protected VariableTree createEnhancedForLoopArrayVariable( ExpressionTree expression, VariableElement variableElement) { TypeMirror arrayType = TreeUtils.typeOf(expression); diff --git a/framework/tests/flow/EnhancedForConversion.java b/framework/tests/flow/EnhancedForConversion.java new file mode 100644 index 000000000000..3a55ca2768d0 --- /dev/null +++ b/framework/tests/flow/EnhancedForConversion.java @@ -0,0 +1,75 @@ +import java.util.List; +import org.checkerframework.framework.testchecker.util.*; + +// The loop variable gets the element type of the iterable expression, even when assignment +// conversion unboxes or widens the element. +public class EnhancedForConversion { + @Odd Integer[] field; + + @Odd Integer[] method() { + throw new Error(); + } + + void unboxList(List<@Odd Integer> list) { + for (int x : list) { + @Odd int y = x; + } + } + + void unboxAndWidenList(List<@Odd Integer> list) { + for (long x : list) { + @Odd long y = x; + } + } + + void unboxWildcardList(List list) { + for (int x : list) { + @Odd int y = x; + } + } + + void unboxAndWidenWildcardList(List list) { + for (long x : list) { + @Odd long y = x; + } + } + + void unboxTypeVariableList(List list) { + for (int x : list) { + @Odd int y = x; + } + } + + void unboxArray(@Odd Integer[] array) { + for (int x : array) { + @Odd int y = x; + } + } + + void unboxAndWidenArray(@Odd Integer[] array) { + for (long x : array) { + @Odd long y = x; + } + } + + void widenArray(@Odd int[] array) { + for (long x : array) { + @Odd long y = x; + } + } + + void unboxArrayField() { + for (int x : field) { + @Odd int y = x; + } + for (int x : this.field) { + @Odd int y = x; + } + } + + void unboxArrayMethod() { + for (int x : method()) { + @Odd int y = x; + } + } +} From 7159813104b1df0a6f954b09d3ac0ab3a7203ebf Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 10:45:41 -0800 Subject: [PATCH 16/98] RLC: an alias that has no @MustCall type in the store cannot satisfy an Obligation All the resource aliases of an Obligation refer to the same resource. A resource alias that has no @MustCall type in the Must Call store -- for example, because it is unassigned on some path to the store's program point -- is absent from the Called Methods store as well, so it cannot satisfy the Obligation. Obligation.getMustCallMethods now omits such an alias when some resource alias has a @MustCall type in the store, rather than falling back to its declared type or its class's default must-call type. That fallback was @MustCall({}) for an Iterator variable, which satisfied the Obligation and hid a leak (#8578). --- .../MustCallConsistencyAnalyzer.java | 98 +++++++++++++------ .../resourceleak/MustCallAliasIterator.java | 68 +++++++++++++ 2 files changed, 134 insertions(+), 32 deletions(-) create mode 100644 checker/tests/resourceleak/MustCallAliasIterator.java diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 2940838442a1..973563a404c7 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -16,7 +16,6 @@ import java.util.Collections; import java.util.Deque; import java.util.EnumSet; -import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; @@ -321,24 +320,50 @@ public boolean derivedFromMustCallAlias() { } /** - * Gets the must-call methods (i.e., the list of methods that must be called to satisfy the - * must-call obligation) of each resource alias represented by this Obligation. + * Returns the must-call methods (i.e., the list of methods that must be called to satisfy the + * must-call obligation) of each resource alias of this Obligation through which the obligation + * can be satisfied. + * + *

If some resource alias of this has a {@code @MustCall} type in the store, then the result + * contains exactly the resource aliases that have one. A resource alias that has no + * {@code @MustCall} type in the store cannot satisfy the obligation, so the result omits it. + * For example, the store lacks a resource alias that is unassigned on some path to the store's + * program point, such as a variable that is assigned the result of a {@code @MustCallAlias} + * method that might throw an exception. The Called Methods store lacks such a resource alias as + * well, so no method is known to have been called on it. Its declared type, however, might be + * {@code @MustCall({})}, as for a variable of type {@code Iterator}; using that type would make + * the obligation trivially satisfied. + * + *

If no resource alias of this has a {@code @MustCall} type in the store, then the result + * contains every resource alias of this, with the must-call type computed by {@link + * #getMustCallValueFromDeclaration}. * * @param rlAtf a Resource Leak Annotated Type Factory - * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis. If this is - * null, then the default MustCall type of each variable's class will be used. - * @return a map from each resource alias of this to a list of its must-call method names, or - * null if the must-call obligations are unsatisfiable (i.e., the value of some tracked - * resource alias of this in the Must Call store is MustCallUnknown) + * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis, or null + * @return a map from resource aliases of this to lists of their must-call method names, whose + * iteration order is that of {@link #resourceAliases}; or null if the must-call obligations + * are unsatisfiable (i.e., no resource alias of this has a {@code @MustCall} type in the + * Must Call store, and the declared type of some resource alias of this is not a + * {@code @MustCall} type, such as MustCallUnknown) */ public @Nullable Map> getMustCallMethods( RLCCalledMethodsAnnotatedTypeFactory rlAtf, @Nullable CFStore mcStore) { - Map> result = new HashMap<>(this.resourceAliases.size()); + Map> result = new LinkedHashMap<>(this.resourceAliases.size()); + for (ResourceAlias alias : this.resourceAliases) { + AnnotationMirror mcAnno = getMustCallValueFromStore(alias, mcStore); + if (mcAnno != null) { + result.put(alias, rlAtf.getMustCallValues(mcAnno)); + } + } + if (!result.isEmpty()) { + return result; + } + MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); - for (ResourceAlias alias : this.resourceAliases) { - AnnotationMirror mcAnno = getMustCallValue(alias, mcStore, mustCallAnnotatedTypeFactory); + AnnotationMirror mcAnno = + getMustCallValueFromDeclaration(alias, mustCallAnnotatedTypeFactory); if (!AnnotationUtils.areSameByName(mcAnno, MustCall.class.getCanonicalName())) { // MustCallUnknown; cannot be satisfied return null; @@ -353,36 +378,44 @@ public boolean derivedFromMustCallAlias() { } /** - * Gets the must-call type associated with the given resource alias, falling back on the - * declared type if there is no refined type for the alias in the store. + * Returns the {@code @MustCall} type of the given resource alias in the given store. * * @param alias a resource alias * @param mcStore the must-call checker's store - * @param mcAtf the must-call checker's annotated type factory - * @return the annotation from the must-call type hierarchy associated with {@code alias} + * @return the {@code @MustCall} annotation of {@code alias} in {@code mcStore}, or null if + * {@code mcStore} is null or has no {@code @MustCall} type for {@code alias} */ - private static AnnotationMirror getMustCallValue( - ResourceAlias alias, @Nullable CFStore mcStore, MustCallAnnotatedTypeFactory mcAtf) { - JavaExpression reference = alias.reference; - CFValue value = mcStore == null ? null : mcStore.getValue(reference); - if (value != null) { - AnnotationMirror result = - AnnotationUtils.getAnnotationByClass(value.getAnnotations(), MustCall.class); - if (result != null) { - return result; - } + private static @Nullable AnnotationMirror getMustCallValueFromStore( + ResourceAlias alias, @Nullable CFStore mcStore) { + CFValue value = mcStore == null ? null : mcStore.getValue(alias.reference); + if (value == null) { + return null; } + return AnnotationUtils.getAnnotationByClass(value.getAnnotations(), MustCall.class); + } + /** + * Returns the must-call type of the given resource alias, ignoring any store. That is its + * declared type, unless its declared type is top. In that case, it is the default must-call + * type of the alias's class; or top if the alias's type is not a class, interface, annotation + * type, or enum (for example, if it is a wildcard type); or bottom if the alias's type is void. + * + * @param alias a resource alias + * @param mcAtf the must-call checker's annotated type factory + * @return the annotation from the must-call type hierarchy associated with {@code alias} + */ + private static AnnotationMirror getMustCallValueFromDeclaration( + ResourceAlias alias, MustCallAnnotatedTypeFactory mcAtf) { AnnotationMirror result = mcAtf.getAnnotatedType(alias.element).getAnnotationInHierarchy(mcAtf.TOP); if (result != null && !AnnotationUtils.areSame(result, mcAtf.TOP)) { return result; } - // There wasn't an @MustCall annotation for it in the store and the type factory has no - // information, so fall back to the default must-call type for the class. + // The declared type is top, so fall back to the default must-call type for the class. // TODO: we currently end up in this case when checking a call to the return type // of a returns-receiver method on something with a MustCall type; for example, // see tests/socket/ZookeeperReport6.java. We should instead use a poly type if we can. + JavaExpression reference = alias.reference; TypeElement typeElt = TypesUtils.getTypeElement(reference.getType()); if (typeElt == null) { // typeElt is null if reference.getType() was not a class, interface, annotation @@ -2359,9 +2392,9 @@ private void checkMustCall( } boolean mustCallSatisfied = false; - for (ResourceAlias alias : obligation.resourceAliases) { - - List mustCallValuesForAlias = mustCallValues.get(alias); + for (Map.Entry> entry : mustCallValues.entrySet()) { + ResourceAlias alias = entry.getKey(); + List mustCallValuesForAlias = entry.getValue(); // optimization when there are no methods to call if (mustCallValuesForAlias.isEmpty()) { mustCallSatisfied = true; @@ -2401,7 +2434,8 @@ private void checkMustCall( if (!mustCallSatisfied) { // Report the error at the first alias' definition. This choice is arbitrary but - // consistent. + // consistent. The first alias might be absent from mustCallValues, so report the + // must-call methods of the first alias that is present. ResourceAlias firstAlias = obligation.resourceAliases.iterator().next(); if (!reportedErrorAliases.contains(firstAlias)) { if (!checker.shouldSkipUses(TreeUtils.elementFromTree(firstAlias.tree))) { @@ -2409,7 +2443,7 @@ private void checkMustCall( checker.reportError( firstAlias.tree, "required.method.not.called", - formatMissingMustCallMethods(mustCallValues.get(firstAlias)), + formatMissingMustCallMethods(mustCallValues.values().iterator().next()), firstAlias.stringForErrorMessage(), firstAlias.reference.getType().toString(), outOfScopeReason); diff --git a/checker/tests/resourceleak/MustCallAliasIterator.java b/checker/tests/resourceleak/MustCallAliasIterator.java new file mode 100644 index 000000000000..747b509aab26 --- /dev/null +++ b/checker/tests/resourceleak/MustCallAliasIterator.java @@ -0,0 +1,68 @@ +// A test of iteration over a resource whose iterator() method returns @MustCallAlias. The +// iterator() call might throw an exception before the iterator variable is assigned, so the store +// at a handler that the call's exceptions reach has no @MustCall type for the iterator variable. +// The iterator variable is a resource alias of the resource. + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.Iterator; +import org.checkerframework.checker.mustcall.qual.MustCallAlias; + +class MustCallAliasIterator { + + static class LineReader extends BufferedReader implements Iterable, Iterator { + @MustCallAlias LineReader(@MustCallAlias Reader in) { + super(in); + } + + LineReader(String filename) throws IOException { + this(new FileReader(filename)); + } + + @Override + @SuppressWarnings("mustcall:override.return") // the iterator is this, which must be closed + public @MustCallAlias Iterator iterator(@MustCallAlias LineReader this) { + return this; + } + + @Override + public boolean hasNext() { + return false; + } + + @Override + public String next() { + throw new Error(); + } + } + + static void process(String s) throws IOException {} + + // Test case for https://github.com/typetools/checker-framework/issues/8578 . + void leakExplicitIterator(String filename) throws IOException { + // :: error: (required.method.not.called) + LineReader lr = new LineReader(filename); + try { + Iterator it = lr.iterator(); + while (it.hasNext()) { + process(it.next()); + } + } catch (Exception e) { + return; + } + lr.close(); + } + + void leakNoIterator(String filename) throws IOException { + // :: error: (required.method.not.called) + LineReader lr = new LineReader(filename); + try { + process(lr.readLine()); + } catch (Exception e) { + return; + } + lr.close(); + } +} From 377e5556f1d48d918b8d34403716b9fca408ddd2 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 10:46:15 -0800 Subject: [PATCH 17/98] Honor @TerminatesExecution on the desugared close() of a try-with-resources statement extendWithMethodInvocationNode, rather than visitMethodInvocation, checks for @TerminatesExecution, so the annotation applies also to calls that the CFG builder synthesizes. extendWithMethodInvocationNode now derives the invoked method from the node and returns nothing. --- .../cfg/builder/CFGTranslationPhaseOne.java | 29 +++++------ framework/tests/flow/Termination.java | 49 +++++++++++++++++++ 2 files changed, 61 insertions(+), 17 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 2370777c9cbd..756db105b54e 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2752,7 +2752,7 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { new MethodInvocationNode( closeCall, closeAccessNode, Collections.emptyList(), getCurrentPath()); closeCallNode.setInSource(false); - extendWithMethodInvocationNode(TreeUtils.elementFromUse(closeCall), closeCallNode); + extendWithMethodInvocationNode(closeCallNode); if (resourceMayBeNull) { addLabelForNextNode(afterCloseLabel); @@ -3379,27 +3379,19 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi MethodInvocationNode node = new MethodInvocationNode(tree, target, arguments, getCurrentPath()); - ExtendedNode extendedNode = extendWithMethodInvocationNode(method, node); - - /* Check for the TerminatesExecution annotation. */ - boolean terminatesExecution = - annotationProvider.getDeclAnnotation(method, TerminatesExecution.class) != null; - if (terminatesExecution) { - extendedNode.setTerminatesExecution(true); - } + extendWithMethodInvocationNode(node); return node; } /** - * Extends the CFG with a MethodInvocationNode, accounting for potential exceptions thrown by the - * invocation. + * Extends the CFG with the given MethodInvocationNode, accounting for potential exceptions thrown + * by the invocation. If the invoked method (the method of {@code node}'s target) is annotated + * {@link TerminatesExecution}, the invocation terminates execution. * - * @param method the invoked method - * @param node the invocation - * @return an ExtendedNode representing the invocation and its possible thrown exceptions + * @param node an invocation */ - private ExtendedNode extendWithMethodInvocationNode( - ExecutableElement method, MethodInvocationNode node) { + private void extendWithMethodInvocationNode(MethodInvocationNode node) { + ExecutableElement method = node.getTarget().getMethod(); List thrownTypes = method.getThrownTypes(); Set thrownSet = new LinkedHashSet<>(thrownTypes.size() + uncheckedExceptionTypes.size()); @@ -3408,7 +3400,10 @@ private ExtendedNode extendWithMethodInvocationNode( // Add types to account for unchecked exceptions thrownSet.addAll(uncheckedExceptionTypes); - return extendWithNodeWithExceptions(node, thrownSet); + ExtendedNode extendedNode = extendWithNodeWithExceptions(node, thrownSet); + if (annotationProvider.getDeclAnnotation(method, TerminatesExecution.class) != null) { + extendedNode.setTerminatesExecution(true); + } } @Override diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index 51dc1334e001..c6eaa33e5580 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -17,4 +17,53 @@ void t1(@Odd String p1, String p2, boolean b1) { } @Odd String l3 = l1; } + + static class TerminatingCloseable implements AutoCloseable { + @Override + @TerminatesExecution + public void close() { + throw new Error(); + } + } + + // The desugared call to close() does not terminate execution, because a try-with-resources + // statement does not call close() if the resource is null. + void t3(@Odd String p1, String p2, boolean b1, TerminatingCloseable c) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (c) {} + } + // :: error: [assignment] + @Odd String l3 = l1; + } + + // The desugared call to close() terminates execution, because the resource is not null. + void t4(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (TerminatingCloseable c = new TerminatingCloseable()) {} + } + @Odd String l3 = l1; + } + + static class ReturningCloseable implements AutoCloseable { + @Override + public void close() {} + } + + // The desugared call to close() returns normally. + void t4Returning(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try (ReturningCloseable c = new ReturningCloseable()) {} + } + // :: error: [assignment] + @Odd String l3 = l1; + } } From 586ab68252db85ca3aa42785f66ccc255d5874b7 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 12:05:45 -0800 Subject: [PATCH 18/98] Fix CI failures: suppress interning warning, add Javadoc; set the boxing conversion's loop in one helper --- .../cfg/builder/CFGTranslationPhaseOne.java | 58 +++++++++++-------- 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 2d263f881c38..38c189b8847a 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1856,12 +1856,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); // If the loop variable is a primitive, the assignment unboxes the result of next(). Save // the iterable expression in the unboxing conversion, too. - MethodInvocationNode unboxingNode = - getBoxingConversion(assignNode.getExpression(), nextCallNode); - if (unboxingNode != null) { - unboxingNode.setIterableExpression(expression); - unboxingNode.setEnhancedForLoop(tree); - } + setLoopOfBoxingConversion(assignNode.getExpression(), nextCallNode, tree); assert statement != null; scan(statement, p); @@ -1958,12 +1953,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { translateAssignment(variable, new LocalVariableNode(variable), arrayAccessNode); // If the loop variable's type and the array's component type differ by a boxing or // unboxing conversion, treat that conversion as an iterator. - MethodInvocationNode boxingNode = - getBoxingConversion(arrayAccessAssignNode.getExpression(), arrayAccessNode); - if (boxingNode != null) { - boxingNode.setIterableExpression(expression); - boxingNode.setEnhancedForLoop(tree); - } + setLoopOfBoxingConversion(arrayAccessAssignNode.getExpression(), arrayAccessNode, tree); assert statement != null; scan(statement, p); @@ -2007,6 +1997,16 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { return null; } + /** + * Returns the declaration of a new, uniquely named variable that is initialized to the iterator + * of an enhanced for loop. + * + * @param iteratorCall the call to {@code iterator()} on the iterable expression of an enhanced + * for loop + * @param variableElement the element of the loop's variable; the new variable has the same + * enclosing element + * @return the declaration of the new iterator variable + */ protected VariableTree createEnhancedForLoopIteratorVariable( MethodInvocationTree iteratorCall, VariableElement variableElement) { TypeMirror iteratorType = TreeUtils.typeOf(iteratorCall); @@ -2022,29 +2022,39 @@ protected VariableTree createEnhancedForLoopIteratorVariable( } /** - * Returns the boxing or unboxing conversion of the given enhanced for loop element, within the - * expression that is assigned to the loop variable. For example, if {@code list} is a {@code - * List}, then in {@code for (long x : list)}, the expression that is assigned to {@code - * x} widens the unboxing conversion of the result of {@code next()}. + * Records the given enhanced for loop, and its iterable expression, in the boxing or unboxing + * conversion of the loop's element within the expression that is assigned to the loop variable. + * Does nothing if that expression contains no such conversion. For example, if {@code list} is a + * {@code List}, then in {@code for (long x : list)}, the expression that is assigned to + * {@code x} widens the unboxing conversion of the result of {@code next()}. * - * @param assignedExpression the expression assigned to an enhanced for loop's variable + * @param assignedExpression the expression assigned to the loop's variable * @param element the loop's element, before any conversion: a call to {@code next()} or an array * access - * @return the boxing or unboxing conversion of {@code element} in {@code assignedExpression}, or - * null if there is none + * @param loop an enhanced for loop */ - private static @Nullable MethodInvocationNode getBoxingConversion( - Node assignedExpression, Node element) { + @SuppressWarnings("interning:not.interned") // identity comparison of nodes + private static void setLoopOfBoxingConversion( + Node assignedExpression, Node element, EnhancedForLoopTree loop) { Node unwidened = assignedExpression instanceof WideningConversionNode widening ? widening.getOperand() : assignedExpression; - if (unwidened != element && unwidened instanceof MethodInvocationNode result) { - return result; + if (unwidened != element && unwidened instanceof MethodInvocationNode conversion) { + conversion.setIterableExpression(loop.getExpression()); + conversion.setEnhancedForLoop(loop); } - return null; } + /** + * Returns the declaration of a new, uniquely named variable that is initialized to the array of + * an enhanced for loop. + * + * @param expression the array expression of an enhanced for loop + * @param variableElement the element of the loop's variable; the new variable has the same + * enclosing element + * @return the declaration of the new array variable + */ protected VariableTree createEnhancedForLoopArrayVariable( ExpressionTree expression, VariableElement variableElement) { TypeMirror arrayType = TreeUtils.typeOf(expression); From b736ada64507b20bf3239091cd9f2941fa795c6e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 12:11:03 -0800 Subject: [PATCH 19/98] Honor @TerminatesExecution on constructors and enhanced-for iterator() calls Route object creations and the desugared iterator(), hasNext(), and next() calls of an enhanced for loop through a shared helper that accounts for thrown exceptions and @TerminatesExecution. Test the break and exceptional paths of a try-with-resources statement's desugared close() call. --- .../cfg/builder/CFGTranslationPhaseOne.java | 36 +++--- framework/tests/flow/Termination.java | 104 +++++++++++++++++- 2 files changed, 118 insertions(+), 22 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 756db105b54e..a2193b70582d 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -66,7 +66,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -1788,7 +1787,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - extendWithNode(iteratorCallNode); + extendWithMethodInvocationNode(iteratorCallNode); translateAssignment( iteratorVariable, new LocalVariableNode(iteratorVariable), iteratorCallNode); @@ -1817,7 +1816,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( hasNextCall, hasNextAccessNode, Collections.emptyList(), getCurrentPath()); hasNextCallNode.setInSource(false); - extendWithNode(hasNextCallNode); + extendWithMethodInvocationNode(hasNextCallNode); extendWithExtendedNode(new ConditionalJump(loopEntry, loopExit)); // Loop body, starting with declaration of the loop iteration variable @@ -1850,7 +1849,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { nextCallNode.setIterableExpression(expression); nextCallNode.setEnhancedForLoop(tree); nextCallNode.setInSource(false); - extendWithNode(nextCallNode); + extendWithMethodInvocationNode(nextCallNode); AssignmentNode assignNode = translateAssignment(variable, new LocalVariableNode(variable), nextCall); @@ -3391,17 +3390,28 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi * @param node an invocation */ private void extendWithMethodInvocationNode(MethodInvocationNode node) { - ExecutableElement method = node.getTarget().getMethod(); - List thrownTypes = method.getThrownTypes(); + extendWithInvocationNode(node, node.getTarget().getMethod()); + } + + /** + * Extends the CFG with the given node, which invokes the given method or constructor, accounting + * for potential exceptions thrown by the invocation. If {@code executable} is annotated {@link + * TerminatesExecution}, the invocation terminates execution. + * + * @param node a method invocation or object creation + * @param executable the method or constructor that {@code node} invokes + */ + private void extendWithInvocationNode(Node node, ExecutableElement executable) { + List thrownTypes = executable.getThrownTypes(); Set thrownSet = - new LinkedHashSet<>(thrownTypes.size() + uncheckedExceptionTypes.size()); + ArraySet.newArraySetOrLinkedHashSet(thrownTypes.size() + uncheckedExceptionTypes.size()); // Add exceptions explicitly mentioned in the throws clause. thrownSet.addAll(thrownTypes); // Add types to account for unchecked exceptions thrownSet.addAll(uncheckedExceptionTypes); ExtendedNode extendedNode = extendWithNodeWithExceptions(node, thrownSet); - if (annotationProvider.getDeclAnnotation(method, TerminatesExecution.class) != null) { + if (annotationProvider.getDeclAnnotation(executable, TerminatesExecution.class) != null) { extendedNode.setTerminatesExecution(true); } } @@ -3446,15 +3456,7 @@ public Node visitNewClass(NewClassTree tree, Void p) { Node node = new ObjectCreationNode(tree, enclosingExprNode, constructorNode, arguments, classbody); - List thrownTypes = constructor.getThrownTypes(); - Set thrownSet = - ArraySet.newArraySetOrLinkedHashSet(thrownTypes.size() + uncheckedExceptionTypes.size()); - // Add exceptions explicitly mentioned in the throws clause. - thrownSet.addAll(thrownTypes); - // Add types to account for unchecked exceptions - thrownSet.addAll(uncheckedExceptionTypes); - - extendWithNodeWithExceptions(node, thrownSet); + extendWithInvocationNode(node, constructor); return node; } diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index c6eaa33e5580..68239cd22756 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -1,3 +1,4 @@ +import java.util.Iterator; import org.checkerframework.dataflow.qual.TerminatesExecution; import org.checkerframework.framework.test.*; import org.checkerframework.framework.testchecker.util.*; @@ -26,9 +27,9 @@ public void close() { } } - // The desugared call to close() does not terminate execution, because a try-with-resources - // statement does not call close() if the resource is null. - void t3(@Odd String p1, String p2, boolean b1, TerminatingCloseable c) { + // The desugared call to close() does not unconditionally terminate execution, because a + // try-with-resources statement does not call close() if the resource is null. + void t2(@Odd String p1, String p2, boolean b1, TerminatingCloseable c) { String l1 = p2; if (b1) { l1 = p1; @@ -40,7 +41,7 @@ void t3(@Odd String p1, String p2, boolean b1, TerminatingCloseable c) { } // The desugared call to close() terminates execution, because the resource is not null. - void t4(@Odd String p1, String p2, boolean b1) { + void t3(@Odd String p1, String p2, boolean b1) { String l1 = p2; if (b1) { l1 = p1; @@ -56,7 +57,7 @@ public void close() {} } // The desugared call to close() returns normally. - void t4Returning(@Odd String p1, String p2, boolean b1) { + void t4(@Odd String p1, String p2, boolean b1) { String l1 = p2; if (b1) { l1 = p1; @@ -66,4 +67,97 @@ void t4Returning(@Odd String p1, String p2, boolean b1) { // :: error: [assignment] @Odd String l3 = l1; } + + static class CheckedException extends Exception {} + + static void throwChecked() throws CheckedException {} + + // The desugared call to close() on the path for a break statement terminates execution, so the + // loop never exits. + void t5(@Odd String p1, String p2, boolean b1, boolean b2) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + while (true) { + try (TerminatingCloseable c = new TerminatingCloseable()) { + if (b2) { + break; + } + } + } + } + @Odd String l3 = l1; + } + + // The desugared call to close() on the exceptional path terminates execution, so the catch + // clause is unreachable. + void t6(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try { + try (TerminatingCloseable c = new TerminatingCloseable()) { + throwChecked(); + } + } catch (CheckedException e) { + } + } + @Odd String l3 = l1; + } + + // Like t6, but the desugared call to close() returns normally, so the catch clause is reachable. + void t6Returning(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + try { + try (ReturningCloseable c = new ReturningCloseable()) { + throwChecked(); + } + } catch (CheckedException e) { + } + } + // :: error: [assignment] + @Odd String l3 = l1; + } + + static class TerminatingIterable implements Iterable { + @Override + @TerminatesExecution + public Iterator iterator() { + throw new Error(); + } + } + + // The desugared call to iterator() terminates execution. + void t7(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + for (Object o : new TerminatingIterable()) {} + } + @Odd String l3 = l1; + } + + static class TerminatingConstructor { + @TerminatesExecution + TerminatingConstructor() { + throw new Error(); + } + } + + // The constructor invocation terminates execution. + void t8(@Odd String p1, String p2, boolean b1) { + String l1 = p2; + if (b1) { + l1 = p1; + } else { + new TerminatingConstructor(); + } + @Odd String l3 = l1; + } } From a1cacb445d584bb68dba1ee9f5176d17b22755ed Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 12:18:05 -0800 Subject: [PATCH 20/98] Test unboxing an Iterable's element and next()'s exceptional edges; correct the boxing-conversion example --- .../cfg/builder/CFGTranslationPhaseOne.java | 11 +++++----- .../tests/flow/EnhancedForConversion.java | 19 ++++++++++++++++++ .../tests/flow/EnhancedForNextException.java | 20 +++++++++++++++++++ 3 files changed, 45 insertions(+), 5 deletions(-) create mode 100644 framework/tests/flow/EnhancedForNextException.java diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 38c189b8847a..0bcf7f7b2880 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1854,8 +1854,9 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { AssignmentNode assignNode = translateAssignment(variable, new LocalVariableNode(variable), nextCallNode); - // If the loop variable is a primitive, the assignment unboxes the result of next(). Save - // the iterable expression in the unboxing conversion, too. + // If the return type of next() is a boxed primitive type and the loop variable is a + // primitive, the assignment unboxes the result of next(). Save the iterable expression in + // the unboxing conversion, too. setLoopOfBoxingConversion(assignNode.getExpression(), nextCallNode, tree); assert statement != null; @@ -2024,9 +2025,9 @@ protected VariableTree createEnhancedForLoopIteratorVariable( /** * Records the given enhanced for loop, and its iterable expression, in the boxing or unboxing * conversion of the loop's element within the expression that is assigned to the loop variable. - * Does nothing if that expression contains no such conversion. For example, if {@code list} is a - * {@code List}, then in {@code for (long x : list)}, the expression that is assigned to - * {@code x} widens the unboxing conversion of the result of {@code next()}. + * Does nothing if that expression contains no such conversion. For example, if {@code array} is + * an {@code Integer[]}, then in {@code for (long x : array)}, the expression that is assigned to + * {@code x} widens the unboxing conversion of the array access. * * @param assignedExpression the expression assigned to the loop's variable * @param element the loop's element, before any conversion: a call to {@code next()} or an array diff --git a/framework/tests/flow/EnhancedForConversion.java b/framework/tests/flow/EnhancedForConversion.java index 3a55ca2768d0..e469a934d9da 100644 --- a/framework/tests/flow/EnhancedForConversion.java +++ b/framework/tests/flow/EnhancedForConversion.java @@ -1,3 +1,4 @@ +import java.util.Iterator; import java.util.List; import org.checkerframework.framework.testchecker.util.*; @@ -40,6 +41,24 @@ void unboxAndWidenWildcardList(List list) { } } + // The return type of iterator() is Iterator<@Odd Integer>, so next() returns an @Odd Integer. + abstract static class OddIntegers implements Iterable<@Odd Integer> { + @Override + public abstract Iterator<@Odd Integer> iterator(); + } + + void unboxIterable(OddIntegers odds) { + for (int x : odds) { + @Odd int y = x; + } + } + + void unboxAndWidenIterable(OddIntegers odds) { + for (long x : odds) { + @Odd long y = x; + } + } + void unboxArray(@Odd Integer[] array) { for (int x : array) { @Odd int y = x; diff --git a/framework/tests/flow/EnhancedForNextException.java b/framework/tests/flow/EnhancedForNextException.java new file mode 100644 index 000000000000..c117a200e5c8 --- /dev/null +++ b/framework/tests/flow/EnhancedForNextException.java @@ -0,0 +1,20 @@ +import org.checkerframework.framework.testchecker.util.*; + +// In an enhanced for loop over an Iterable, the call to next() can throw an exception. +public class EnhancedForNextException { + void mayThrow() {} + + // The call to next() can throw an exception after an iteration has assigned p2 to l1. + void nextThrows(@Odd String p1, String p2, Iterable iterable) { + String l1 = p1; + try { + mayThrow(); + for (String s : iterable) { + l1 = p2; + } + } catch (RuntimeException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } +} From 9befe187732becdc10dc793b6fbbe9eb2d1e33ce Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 12:18:25 -0800 Subject: [PATCH 21/98] RLC: an alias that has no value in the Must Call store gets the must-call methods of the other aliases An alias missing from the Must Call store is checked against the union of the must-call methods of the aliases that are in the store, rather than being excluded or using its declared type. --- .../MustCallConsistencyAnalyzer.java | 133 +++++++++--------- 1 file changed, 70 insertions(+), 63 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 973563a404c7..08c0000bb51f 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -16,6 +16,7 @@ import java.util.Collections; import java.util.Deque; import java.util.EnumSet; +import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; @@ -320,50 +321,54 @@ public boolean derivedFromMustCallAlias() { } /** - * Returns the must-call methods (i.e., the list of methods that must be called to satisfy the - * must-call obligation) of each resource alias of this Obligation through which the obligation - * can be satisfied. + * Gets the must-call methods (i.e., the list of methods that must be called to satisfy the + * must-call obligation) of each resource alias represented by this Obligation. * - *

If some resource alias of this has a {@code @MustCall} type in the store, then the result - * contains exactly the resource aliases that have one. A resource alias that has no - * {@code @MustCall} type in the store cannot satisfy the obligation, so the result omits it. - * For example, the store lacks a resource alias that is unassigned on some path to the store's - * program point, such as a variable that is assigned the result of a {@code @MustCallAlias} - * method that might throw an exception. The Called Methods store lacks such a resource alias as - * well, so no method is known to have been called on it. Its declared type, however, might be - * {@code @MustCall({})}, as for a variable of type {@code Iterator}; using that type would make - * the obligation trivially satisfied. + *

The must-call methods of a resource alias that has a value in the store come from that + * value, or from the alias's declaration (see {@link #getMustCallValue}). * - *

If no resource alias of this has a {@code @MustCall} type in the store, then the result - * contains every resource alias of this, with the must-call type computed by {@link - * #getMustCallValueFromDeclaration}. + *

A resource alias that has no value in the store gets the must-call methods of the + * resource, which is the union of the must-call methods of the resource aliases that have a + * value in the store. For example, the store has no value for a resource alias that is + * unassigned on some path to the store's program point, such as a variable that is assigned the + * result of a {@code @MustCallAlias} method that might throw an exception. The declared type of + * such a resource alias might be {@code @MustCall({})}, as for a variable of type {@code + * Iterator}; using that type would make the obligation trivially satisfied. If no resource + * alias has a value in the store, then each one gets the must-call methods of its declaration. * * @param rlAtf a Resource Leak Annotated Type Factory - * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis, or null - * @return a map from resource aliases of this to lists of their must-call method names, whose - * iteration order is that of {@link #resourceAliases}; or null if the must-call obligations - * are unsatisfiable (i.e., no resource alias of this has a {@code @MustCall} type in the - * Must Call store, and the declared type of some resource alias of this is not a - * {@code @MustCall} type, such as MustCallUnknown) + * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis. If this is + * null, then the default MustCall type of each variable's class will be used. + * @return a map from each resource alias of this to a list of its must-call method names, or + * null if the must-call obligations are unsatisfiable (i.e., the value of some tracked + * resource alias of this in the Must Call store is MustCallUnknown) */ public @Nullable Map> getMustCallMethods( RLCCalledMethodsAnnotatedTypeFactory rlAtf, @Nullable CFStore mcStore) { - Map> result = new LinkedHashMap<>(this.resourceAliases.size()); - for (ResourceAlias alias : this.resourceAliases) { - AnnotationMirror mcAnno = getMustCallValueFromStore(alias, mcStore); - if (mcAnno != null) { - result.put(alias, rlAtf.getMustCallValues(mcAnno)); + Map> result = new HashMap<>(this.resourceAliases.size()); + MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = + rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); + + // The resource aliases of this that have no value in mcStore, if some other resource alias + // of this does. + List aliasesNotInStore = new ArrayList<>(); + if (mcStore != null) { + for (ResourceAlias alias : this.resourceAliases) { + if (mcStore.getValue(alias.reference) == null) { + aliasesNotInStore.add(alias); + } + } + if (aliasesNotInStore.size() == this.resourceAliases.size()) { + // No resource alias has a value in the store, so use the declarations. + aliasesNotInStore.clear(); } - } - if (!result.isEmpty()) { - return result; } - MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = - rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); for (ResourceAlias alias : this.resourceAliases) { - AnnotationMirror mcAnno = - getMustCallValueFromDeclaration(alias, mustCallAnnotatedTypeFactory); + if (aliasesNotInStore.contains(alias)) { + continue; + } + AnnotationMirror mcAnno = getMustCallValue(alias, mcStore, mustCallAnnotatedTypeFactory); if (!AnnotationUtils.areSameByName(mcAnno, MustCall.class.getCanonicalName())) { // MustCallUnknown; cannot be satisfied return null; @@ -374,48 +379,51 @@ public boolean derivedFromMustCallAlias() { // TODO: add an assertion that annoVals is non-empty and address any failures result.put(alias, annoVals); } - return result; - } - /** - * Returns the {@code @MustCall} type of the given resource alias in the given store. - * - * @param alias a resource alias - * @param mcStore the must-call checker's store - * @return the {@code @MustCall} annotation of {@code alias} in {@code mcStore}, or null if - * {@code mcStore} is null or has no {@code @MustCall} type for {@code alias} - */ - private static @Nullable AnnotationMirror getMustCallValueFromStore( - ResourceAlias alias, @Nullable CFStore mcStore) { - CFValue value = mcStore == null ? null : mcStore.getValue(alias.reference); - if (value == null) { - return null; + if (!aliasesNotInStore.isEmpty()) { + Set resourceMustCallMethods = new LinkedHashSet<>(); + for (List mustCallMethods : result.values()) { + resourceMustCallMethods.addAll(mustCallMethods); + } + List resourceMustCallMethodsList = new ArrayList<>(resourceMustCallMethods); + for (ResourceAlias alias : aliasesNotInStore) { + result.put(alias, resourceMustCallMethodsList); + } } - return AnnotationUtils.getAnnotationByClass(value.getAnnotations(), MustCall.class); + return result; } /** - * Returns the must-call type of the given resource alias, ignoring any store. That is its - * declared type, unless its declared type is top. In that case, it is the default must-call - * type of the alias's class; or top if the alias's type is not a class, interface, annotation - * type, or enum (for example, if it is a wildcard type); or bottom if the alias's type is void. + * Gets the must-call type associated with the given resource alias, falling back on the + * declared type if there is no refined type for the alias in the store. * * @param alias a resource alias + * @param mcStore the must-call checker's store * @param mcAtf the must-call checker's annotated type factory * @return the annotation from the must-call type hierarchy associated with {@code alias} */ - private static AnnotationMirror getMustCallValueFromDeclaration( - ResourceAlias alias, MustCallAnnotatedTypeFactory mcAtf) { + private static AnnotationMirror getMustCallValue( + ResourceAlias alias, @Nullable CFStore mcStore, MustCallAnnotatedTypeFactory mcAtf) { + JavaExpression reference = alias.reference; + CFValue value = mcStore == null ? null : mcStore.getValue(reference); + if (value != null) { + AnnotationMirror result = + AnnotationUtils.getAnnotationByClass(value.getAnnotations(), MustCall.class); + if (result != null) { + return result; + } + } + AnnotationMirror result = mcAtf.getAnnotatedType(alias.element).getAnnotationInHierarchy(mcAtf.TOP); if (result != null && !AnnotationUtils.areSame(result, mcAtf.TOP)) { return result; } - // The declared type is top, so fall back to the default must-call type for the class. + // There wasn't an @MustCall annotation for it in the store and the type factory has no + // information, so fall back to the default must-call type for the class. // TODO: we currently end up in this case when checking a call to the return type // of a returns-receiver method on something with a MustCall type; for example, // see tests/socket/ZookeeperReport6.java. We should instead use a poly type if we can. - JavaExpression reference = alias.reference; TypeElement typeElt = TypesUtils.getTypeElement(reference.getType()); if (typeElt == null) { // typeElt is null if reference.getType() was not a class, interface, annotation @@ -2392,9 +2400,9 @@ private void checkMustCall( } boolean mustCallSatisfied = false; - for (Map.Entry> entry : mustCallValues.entrySet()) { - ResourceAlias alias = entry.getKey(); - List mustCallValuesForAlias = entry.getValue(); + for (ResourceAlias alias : obligation.resourceAliases) { + + List mustCallValuesForAlias = mustCallValues.get(alias); // optimization when there are no methods to call if (mustCallValuesForAlias.isEmpty()) { mustCallSatisfied = true; @@ -2434,8 +2442,7 @@ private void checkMustCall( if (!mustCallSatisfied) { // Report the error at the first alias' definition. This choice is arbitrary but - // consistent. The first alias might be absent from mustCallValues, so report the - // must-call methods of the first alias that is present. + // consistent. ResourceAlias firstAlias = obligation.resourceAliases.iterator().next(); if (!reportedErrorAliases.contains(firstAlias)) { if (!checker.shouldSkipUses(TreeUtils.elementFromTree(firstAlias.tree))) { @@ -2443,7 +2450,7 @@ private void checkMustCall( checker.reportError( firstAlias.tree, "required.method.not.called", - formatMissingMustCallMethods(mustCallValues.values().iterator().next()), + formatMissingMustCallMethods(mustCallValues.get(firstAlias)), firstAlias.stringForErrorMessage(), firstAlias.reference.getType().toString(), outOfScopeReason); From 884dd4cb73c3b318fb5bdd02bf814ba7c642856f Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 12:28:50 -0800 Subject: [PATCH 22/98] Add a test of an alias that is in the Called Methods store but not the Must Call store --- .../resourceleak/AliasNotInMustCallStore.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 checker/tests/resourceleak/AliasNotInMustCallStore.java diff --git a/checker/tests/resourceleak/AliasNotInMustCallStore.java b/checker/tests/resourceleak/AliasNotInMustCallStore.java new file mode 100644 index 000000000000..45808865fb1a --- /dev/null +++ b/checker/tests/resourceleak/AliasNotInMustCallStore.java @@ -0,0 +1,59 @@ +// A test of a resource alias that is unassigned on some path to a method exit, and through which +// the must-call method is called. At the check on the edge from a conditional block to the exit +// block, the Must Call store is the exit block's input, which merges every path to the exit, so it +// has no value for the alias. The Called Methods store is the edge's own store, which records +// that close() was called on the alias. The checker should issue no error. + +import java.io.FileInputStream; +import java.io.IOException; + +class AliasNotInMustCallStore { + + void whileLoop(boolean b, boolean c) throws IOException { + FileInputStream s = new FileInputStream("x"); + if (b) { + s.close(); + return; + } + FileInputStream t = s; + t.close(); + while (c) {} + } + + void ifReturn(boolean b, boolean c) throws IOException { + FileInputStream s = new FileInputStream("x"); + if (b) { + s.close(); + return; + } + FileInputStream t = s; + t.close(); + if (c) { + return; + } + } + + void assertStatement(boolean b, boolean c) throws IOException { + FileInputStream s = new FileInputStream("x"); + if (b) { + s.close(); + return; + } + FileInputStream t = s; + t.close(); + assert c; + } + + void ifAtEnd(boolean b, boolean c) throws IOException { + FileInputStream s = new FileInputStream("x"); + if (b) { + s.close(); + return; + } + FileInputStream t = s; + t.close(); + if (c) { + System.out.println(); + } + } +} From d0b79bad0938756122aba3a5b44a92851585a477 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 12:38:34 -0800 Subject: [PATCH 23/98] Simplify getMustCallMethods, make its union deterministic, and correct its Javadoc --- .../MustCallConsistencyAnalyzer.java | 92 ++++++++++++------- 1 file changed, 57 insertions(+), 35 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 08c0000bb51f..9302b3afff11 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -16,7 +16,6 @@ import java.util.Collections; import java.util.Deque; import java.util.EnumSet; -import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; @@ -321,7 +320,7 @@ public boolean derivedFromMustCallAlias() { } /** - * Gets the must-call methods (i.e., the list of methods that must be called to satisfy the + * Returns the must-call methods (i.e., the list of methods that must be called to satisfy the * must-call obligation) of each resource alias represented by this Obligation. * *

The must-call methods of a resource alias that has a value in the store come from that @@ -337,62 +336,85 @@ public boolean derivedFromMustCallAlias() { * alias has a value in the store, then each one gets the must-call methods of its declaration. * * @param rlAtf a Resource Leak Annotated Type Factory - * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis. If this is - * null, then the default MustCall type of each variable's class will be used. - * @return a map from each resource alias of this to a list of its must-call method names, or - * null if the must-call obligations are unsatisfiable (i.e., the value of some tracked - * resource alias of this in the Must Call store is MustCallUnknown) + * @param mcStore a CFStore produced by the MustCall checker's dataflow analysis, or null. If + * this is null, then each resource alias gets the must-call methods of its declaration. + * @return a map from each resource alias of this to the list of method names that must be + * called through that resource alias to satisfy the must-call obligation; or null if the + * must-call obligation is unsatisfiable (i.e., the must-call type that some resource alias + * of this gets is not a {@code @MustCall} type, such as MustCallUnknown) */ public @Nullable Map> getMustCallMethods( RLCCalledMethodsAnnotatedTypeFactory rlAtf, @Nullable CFStore mcStore) { - Map> result = new HashMap<>(this.resourceAliases.size()); MustCallAnnotatedTypeFactory mustCallAnnotatedTypeFactory = rlAtf.getTypeFactoryOfSubchecker(MustCallChecker.class); + // A LinkedHashMap, so that the union below is deterministic. + Map> result = new LinkedHashMap<>(this.resourceAliases.size()); - // The resource aliases of this that have no value in mcStore, if some other resource alias - // of this does. - List aliasesNotInStore = new ArrayList<>(); - if (mcStore != null) { - for (ResourceAlias alias : this.resourceAliases) { - if (mcStore.getValue(alias.reference) == null) { - aliasesNotInStore.add(alias); + for (ResourceAlias alias : this.resourceAliases) { + if (mcStore == null || mcStore.getValue(alias.reference) != null) { + List mustCallMethods = + getMustCallMethodsOfAlias(alias, mcStore, mustCallAnnotatedTypeFactory, rlAtf); + if (mustCallMethods == null) { + return null; } - } - if (aliasesNotInStore.size() == this.resourceAliases.size()) { - // No resource alias has a value in the store, so use the declarations. - aliasesNotInStore.clear(); + result.put(alias, mustCallMethods); } } - for (ResourceAlias alias : this.resourceAliases) { - if (aliasesNotInStore.contains(alias)) { - continue; - } - AnnotationMirror mcAnno = getMustCallValue(alias, mcStore, mustCallAnnotatedTypeFactory); - if (!AnnotationUtils.areSameByName(mcAnno, MustCall.class.getCanonicalName())) { - // MustCallUnknown; cannot be satisfied - return null; + if (result.isEmpty()) { + // No resource alias has a value in the store, so use the declarations. + for (ResourceAlias alias : this.resourceAliases) { + List mustCallMethods = + getMustCallMethodsOfAlias(alias, mcStore, mustCallAnnotatedTypeFactory, rlAtf); + if (mustCallMethods == null) { + return null; + } + result.put(alias, mustCallMethods); } - List annoVals = rlAtf.getMustCallValues(mcAnno); - // Really, annoVals should never be empty here; we should not have created the - // obligation in the first place. - // TODO: add an assertion that annoVals is non-empty and address any failures - result.put(alias, annoVals); + return result; } - if (!aliasesNotInStore.isEmpty()) { + if (result.size() < this.resourceAliases.size()) { Set resourceMustCallMethods = new LinkedHashSet<>(); for (List mustCallMethods : result.values()) { resourceMustCallMethods.addAll(mustCallMethods); } List resourceMustCallMethodsList = new ArrayList<>(resourceMustCallMethods); - for (ResourceAlias alias : aliasesNotInStore) { - result.put(alias, resourceMustCallMethodsList); + for (ResourceAlias alias : this.resourceAliases) { + result.putIfAbsent(alias, resourceMustCallMethodsList); } } return result; } + /** + * Returns the must-call methods of the given resource alias, from its value in the given store + * or from its declaration (see {@link #getMustCallValue}). + * + * @param alias a resource alias + * @param mcStore the must-call checker's store, or null + * @param mcAtf the must-call checker's annotated type factory + * @param rlAtf the Resource Leak Annotated Type Factory + * @return the must-call methods of {@code alias}, or null if its must-call type is not a + * {@code @MustCall} type, such as MustCallUnknown + */ + private static @Nullable List getMustCallMethodsOfAlias( + ResourceAlias alias, + @Nullable CFStore mcStore, + MustCallAnnotatedTypeFactory mcAtf, + RLCCalledMethodsAnnotatedTypeFactory rlAtf) { + AnnotationMirror mcAnno = getMustCallValue(alias, mcStore, mcAtf); + if (!AnnotationUtils.areSameByName(mcAnno, MustCall.class.getCanonicalName())) { + // MustCallUnknown; cannot be satisfied + return null; + } + List annoVals = rlAtf.getMustCallValues(mcAnno); + // Really, annoVals should never be empty here; we should not have created the + // obligation in the first place. + // TODO: add an assertion that annoVals is non-empty and address any failures + return annoVals; + } + /** * Gets the must-call type associated with the given resource alias, falling back on the * declared type if there is no refined type for the alias in the store. From c55947edfb0e3325b01152ccb58d999833e44562 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 13:30:26 -0800 Subject: [PATCH 24/98] Give the desugared iterator() call exceptional successors only if it terminates execution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On an exceptional successor of the iterator() call, the iterator variable is unassigned. When such a path merged with a path on which the iterator variable is a @MustCallAlias of the Iterable, the Resource Leak Checker issued a false positive required.method.not.known error, as in plume-lib/multi-version-control. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- .../TryWithResourcesEnhancedFor.java | 41 +++++++++++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 13 +++++- 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 checker/tests/resourceleak/TryWithResourcesEnhancedFor.java diff --git a/checker/tests/resourceleak/TryWithResourcesEnhancedFor.java b/checker/tests/resourceleak/TryWithResourcesEnhancedFor.java new file mode 100644 index 000000000000..c85ebb1d1662 --- /dev/null +++ b/checker/tests/resourceleak/TryWithResourcesEnhancedFor.java @@ -0,0 +1,41 @@ +// An enhanced for loop, inside a try-with-resources statement, that iterates over the resource. +// The resource's iterator is a @MustCallAlias of the resource. + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.Iterator; +import org.checkerframework.checker.mustcall.qual.MustCallAlias; + +class TryWithResourcesEnhancedFor { + + abstract static class LineReader extends BufferedReader + implements Iterable, Iterator { + + @MustCallAlias LineReader(@MustCallAlias Reader r) { + super(r); + } + + @Override + @SuppressWarnings("mustcall:override.return") + public @MustCallAlias Iterator iterator(@MustCallAlias LineReader this) { + return this; + } + } + + static native @MustCallAlias LineReader makeLineReader(@MustCallAlias Reader r); + + static class CheckedException extends IOException {} + + static native void mightThrow() throws CheckedException; + + void test(File file) throws IOException { + try (LineReader lr = makeLineReader(new FileReader(file))) { + for (String line : lr) { + mightThrow(); + } + } + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index a2193b70582d..3cad4681935d 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1787,7 +1787,18 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - extendWithMethodInvocationNode(iteratorCallNode); + // The iterator() call has exceptional successors only if it terminates execution. On an + // exceptional successor, the iterator variable is unassigned. If such a successor merges + // with a path on which the iterator variable is a @MustCallAlias of the Iterable, then the + // Resource Leak Checker cannot determine the iterator variable's must-call type and reports + // a false positive. + if (annotationProvider.getDeclAnnotation( + iteratorCallNode.getTarget().getMethod(), TerminatesExecution.class) + != null) { + extendWithMethodInvocationNode(iteratorCallNode); + } else { + extendWithNode(iteratorCallNode); + } translateAssignment( iteratorVariable, new LocalVariableNode(iteratorVariable), iteratorCallNode); From 9e2b0b2aca846463bc8f045177e97fe176ba394e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 13:59:25 -0800 Subject: [PATCH 25/98] Comment --- .../checker/resourceleak/MustCallConsistencyAnalyzer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java index 9302b3afff11..919ee79341c9 100644 --- a/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java +++ b/checker/src/main/java/org/checkerframework/checker/resourceleak/MustCallConsistencyAnalyzer.java @@ -375,6 +375,7 @@ public boolean derivedFromMustCallAlias() { } if (result.size() < this.resourceAliases.size()) { + // At least one alias has a store value, and at least one does not. Set resourceMustCallMethods = new LinkedHashSet<>(); for (List mustCallMethods : result.values()) { resourceMustCallMethods.addAll(mustCallMethods); From 285254df3f4a5f497c42cb33c8a7d1a425e32d88 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 14:09:27 -0800 Subject: [PATCH 26/98] Comment --- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 3cad4681935d..2d8a3b9f1ce9 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1787,11 +1787,13 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - // The iterator() call has exceptional successors only if it terminates execution. On an - // exceptional successor, the iterator variable is unassigned. If such a successor merges - // with a path on which the iterator variable is a @MustCallAlias of the Iterable, then the - // Resource Leak Checker cannot determine the iterator variable's must-call type and reports - // a false positive. + // The iterator() call gets exceptional successors only if it terminates execution. + // Exceptional successors in general would cause Resource Leak Checker false positives: on + // an exceptional successor of iterator(), the iterator variable is unassigned, and where + // that path merges with one on which the iterator variable is a @MustCallAlias of the + // Iterable (such as an exceptional successor of hasNext() or next()), the checker cannot + // determine the iterator variable's must-call type. If iterator() terminates execution, + // then hasNext() and next() are unreachable, so no such merge occurs. if (annotationProvider.getDeclAnnotation( iteratorCallNode.getTarget().getMethod(), TerminatesExecution.class) != null) { From 00430d5852320a2bed4c7930bc01cb8867930be0 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 10:11:14 -0800 Subject: [PATCH 27/98] Don't refine a receiver after a call whose arguments may reassign it --- .../checker/nullness/NullnessTransfer.java | 93 ++++++++++++++++++- .../nullness/ReceiverRefinementInCatch.java | 46 +++++++++ 2 files changed, 138 insertions(+), 1 deletion(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 70fa18e0a821..ae6464c5e26e 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -1,8 +1,12 @@ package org.checkerframework.checker.nullness; +import com.sun.source.tree.AssignmentTree; +import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; +import com.sun.source.tree.NewClassTree; +import com.sun.source.util.TreeScanner; import java.util.List; import java.util.Map; import javax.lang.model.element.AnnotationMirror; @@ -419,10 +423,15 @@ public TransferResult visitMethodInvocation( // MethodAccessNode. A call tests its receiver for nullness after evaluating its arguments, so // neither the arguments nor a handler for the call's NullPointerException may assume that the // receiver is non-null. + // The refinement applies to the receiver expression, not to the value that was evaluated + // before the arguments, so it is skipped if evaluating the arguments might reassign the + // receiver expression, as in `r.m(r = null)`. + JavaExpression receiverExpr = JavaExpression.fromNode(receiver); if (!n.getTarget().isStatic() && (nonNullAssumptionAfterInvocation || isMethodSideEffectFree - || !JavaExpression.fromNode(receiver).isAssignableByOtherCode())) { + || !receiverExpr.isAssignableByOtherCode()) + && !argumentsMayReassign(tree.getArguments(), receiverExpr)) { // Make receiver non-null. makeNonNull(result, receiver); } @@ -465,6 +474,88 @@ public TransferResult visitMethodInvocation( return result; } + /** + * Returns true if evaluating the given method arguments might reassign the given receiver + * expression or a subexpression of it. This is conservative. It returns true if an argument + * assigns any part of the receiver expression. If the receiver expression is assignable by other + * code, it also returns true if an argument assigns a non-local variable or (unless {@link + * #nonNullAssumptionAfterInvocation} is set) invokes a method or constructor that is not + * side-effect-free. + * + * @param arguments the arguments of a method invocation + * @param receiverExpr the receiver of the method invocation + * @return true if evaluating {@code arguments} might reassign {@code receiverExpr} + */ + private boolean argumentsMayReassign( + List arguments, JavaExpression receiverExpr) { + if (arguments.isEmpty()) { + return false; + } + boolean receiverAssignableByOtherCode = receiverExpr.isAssignableByOtherCode(); + TreeScanner scanner = + new TreeScanner() { + @Override + public Boolean reduce(Boolean r1, Boolean r2) { + return Boolean.TRUE.equals(r1) || Boolean.TRUE.equals(r2); + } + + @Override + public Boolean visitAssignment(AssignmentTree tree, Void p) { + return assignsReceiver(tree.getVariable()) || super.visitAssignment(tree, p); + } + + @Override + public Boolean visitCompoundAssignment(CompoundAssignmentTree tree, Void p) { + return assignsReceiver(tree.getVariable()) || super.visitCompoundAssignment(tree, p); + } + + @Override + public Boolean visitMethodInvocation(MethodInvocationTree tree, Void p) { + return mayHaveSideEffect(TreeUtils.elementFromUse(tree)) + || super.visitMethodInvocation(tree, p); + } + + @Override + public Boolean visitNewClass(NewClassTree tree, Void p) { + return mayHaveSideEffect(TreeUtils.elementFromUse(tree)) + || super.visitNewClass(tree, p); + } + + /** + * Returns true if assigning the given variable might reassign the receiver. + * + * @param variable the left-hand side of an assignment + * @return true if assigning {@code variable} might reassign the receiver + */ + private boolean assignsReceiver(ExpressionTree variable) { + JavaExpression assigned = JavaExpression.fromTree(variable); + if (receiverExpr.containsSyntacticEqualJavaExpression(assigned)) { + return true; + } + return receiverAssignableByOtherCode && !(assigned instanceof LocalVariable); + } + + /** + * Returns true if invoking the given method or constructor might reassign the receiver. + * + * @param executable a method or constructor + * @return true if invoking {@code executable} might reassign the receiver + */ + private boolean mayHaveSideEffect(ExecutableElement executable) { + return receiverAssignableByOtherCode + && !nonNullAssumptionAfterInvocation + && !atypeFactory.isSideEffectFree(executable) + && !PurityUtils.isSideEffectFree(atypeFactory, executable); + } + }; + for (ExpressionTree argument : arguments) { + if (Boolean.TRUE.equals(scanner.scan(argument, null))) { + return true; + } + } + return false; + } + /** * Returns true if {@code mapOrSubtype}'s value type (the V type argument to Map) is @Nullable. * diff --git a/checker/tests/nullness/ReceiverRefinementInCatch.java b/checker/tests/nullness/ReceiverRefinementInCatch.java index 656815da2635..c0c982c373d6 100644 --- a/checker/tests/nullness/ReceiverRefinementInCatch.java +++ b/checker/tests/nullness/ReceiverRefinementInCatch.java @@ -20,4 +20,50 @@ void afterNormalCompletion(@Nullable Object o) { // The call completed normally, so o is non-null. o.hashCode(); } + + void accept(@Nullable Object o) {} + + // The receiver is evaluated before the argument, so the call succeeds, but afterward r is null. + void argumentReassignsReceiver(@Nullable ReceiverRefinementInCatch r) { + if (r == null) { + return; + } + r.accept(r = null); + // :: error: (dereference.of.nullable) + r.toString(); + } + + @Nullable ReceiverRefinementInCatch f; + + void clearF() { + f = null; + } + + @org.checkerframework.dataflow.qual.SideEffectFree + void sefAccept(@Nullable Object o) {} + + void argumentReassignsFieldReceiver() { + // :: error: (dereference.of.nullable) + f.sefAccept(f = null); + // :: error: (dereference.of.nullable) + f.toString(); + } + + void argumentSideEffectOnFieldReceiver() { + // :: error: (dereference.of.nullable) + f.sefAccept(clearFAndReturn()); + // :: error: (dereference.of.nullable) + f.toString(); + } + + @Nullable Object clearFAndReturn() { + clearF(); + return null; + } + + void argumentDoesNotReassignReceiver(@Nullable Object o, @Nullable Object other) { + // :: error: (dereference.of.nullable) + o.equals(other = null); + o.hashCode(); + } } From 4f252662413f64a150535c4ac801ebb1196cc02a Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 11:22:20 -0800 Subject: [PATCH 28/98] Fix the build after merging branch 'master' --- .../checkerframework/checker/nullness/NullnessTransfer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index ae6464c5e26e..b47eb46eeb63 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -521,7 +521,7 @@ public Boolean visitNewClass(NewClassTree tree, Void p) { || super.visitNewClass(tree, p); } - /** + /* * Returns true if assigning the given variable might reassign the receiver. * * @param variable the left-hand side of an assignment @@ -535,7 +535,7 @@ private boolean assignsReceiver(ExpressionTree variable) { return receiverAssignableByOtherCode && !(assigned instanceof LocalVariable); } - /** + /* * Returns true if invoking the given method or constructor might reassign the receiver. * * @param executable a method or constructor From 399c53e4094b0bfe43a0e2a05ed7948cfb6581f7 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 13:13:36 -0800 Subject: [PATCH 29/98] Detect increment and decrement of receiver subexpressions in method arguments --- .../checker/nullness/NullnessTransfer.java | 18 +++++++++++++++++ .../nullness/ReceiverRefinementInCatch.java | 20 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index b47eb46eeb63..c85e19cd4609 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -6,6 +6,7 @@ import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.UnaryTree; import com.sun.source.util.TreeScanner; import java.util.List; import java.util.Map; @@ -509,6 +510,23 @@ public Boolean visitCompoundAssignment(CompoundAssignmentTree tree, Void p) { return assignsReceiver(tree.getVariable()) || super.visitCompoundAssignment(tree, p); } + @Override + public Boolean visitUnary(UnaryTree tree, Void p) { + switch (tree.getKind()) { + case PREFIX_INCREMENT: + case PREFIX_DECREMENT: + case POSTFIX_INCREMENT: + case POSTFIX_DECREMENT: + if (assignsReceiver(tree.getExpression())) { + return true; + } + break; + default: + break; + } + return super.visitUnary(tree, p); + } + @Override public Boolean visitMethodInvocation(MethodInvocationTree tree, Void p) { return mayHaveSideEffect(TreeUtils.elementFromUse(tree)) diff --git a/checker/tests/nullness/ReceiverRefinementInCatch.java b/checker/tests/nullness/ReceiverRefinementInCatch.java index c0c982c373d6..d966dac7b8af 100644 --- a/checker/tests/nullness/ReceiverRefinementInCatch.java +++ b/checker/tests/nullness/ReceiverRefinementInCatch.java @@ -61,6 +61,26 @@ void argumentSideEffectOnFieldReceiver() { return null; } + // The argument increments the index of the receiver, so afterward a[i] denotes a different + // array element. + void argumentIncrementsReceiverIndex(@Nullable ReceiverRefinementInCatch[] a, int i) { + if (a[i] == null) { + return; + } + a[i].sefAccept(i++); + // :: error: (dereference.of.nullable) + a[i].toString(); + } + + void argumentDecrementsReceiverIndex(@Nullable ReceiverRefinementInCatch[] a, int i) { + if (a[i] == null) { + return; + } + a[i].sefAccept(--i); + // :: error: (dereference.of.nullable) + a[i].toString(); + } + void argumentDoesNotReassignReceiver(@Nullable Object o, @Nullable Object other) { // :: error: (dereference.of.nullable) o.equals(other = null); From 6f73bc2926da7fceb5cfa9a079666512c1bceda3 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 15:59:09 -0800 Subject: [PATCH 30/98] Fix the build after merging branch 'terminates-execution-check' --- .../checker/nullness/NullnessTransfer.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index c85e19cd4609..cc210db849a4 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -513,16 +513,12 @@ public Boolean visitCompoundAssignment(CompoundAssignmentTree tree, Void p) { @Override public Boolean visitUnary(UnaryTree tree, Void p) { switch (tree.getKind()) { - case PREFIX_INCREMENT: - case PREFIX_DECREMENT: - case POSTFIX_INCREMENT: - case POSTFIX_DECREMENT: + case PREFIX_INCREMENT, PREFIX_DECREMENT, POSTFIX_INCREMENT, POSTFIX_DECREMENT -> { if (assignsReceiver(tree.getExpression())) { return true; } - break; - default: - break; + } + default -> {} } return super.visitUnary(tree, p); } From 2564c40af80756d272732d7812613293c49dd267 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 18:54:21 -0800 Subject: [PATCH 31/98] Give the desugared iterator() call of an enhanced for loop exceptional edges unconditionally --- .../EnhancedForIteratorPostcondition.java | 35 +++++++++++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 15 +------- 2 files changed, 36 insertions(+), 14 deletions(-) create mode 100644 checker/tests/nullness/EnhancedForIteratorPostcondition.java diff --git a/checker/tests/nullness/EnhancedForIteratorPostcondition.java b/checker/tests/nullness/EnhancedForIteratorPostcondition.java new file mode 100644 index 000000000000..123ae1944563 --- /dev/null +++ b/checker/tests/nullness/EnhancedForIteratorPostcondition.java @@ -0,0 +1,35 @@ +// The desugared call to iterator() of an enhanced for loop can throw an exception before it +// establishes its postcondition. + +import java.util.Collections; +import java.util.Iterator; +import org.checkerframework.checker.nullness.qual.EnsuresNonNull; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; + +class EnhancedForIteratorPostcondition { + + static class FieldSettingIterable implements Iterable { + @MonotonicNonNull Object f; + + @Override + @EnsuresNonNull("f") + public Iterator iterator() { + f = new Object(); + return Collections.emptyIterator(); + } + } + + void afterLoop(FieldSettingIterable it) { + for (String s : it) {} + it.f.toString(); + } + + void inCatch(FieldSettingIterable it) { + try { + for (String s : it) {} + } catch (RuntimeException e) { + // :: error: (dereference.of.nullable) + it.f.toString(); + } + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index ba1c9e81a2bd..f4dc4458b09d 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1787,20 +1787,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); iteratorCallNode.setInSource(false); - // The iterator() call gets exceptional successors only if it terminates execution. - // Exceptional successors in general would cause Resource Leak Checker false positives: on - // an exceptional successor of iterator(), the iterator variable is unassigned, and where - // that path merges with one on which the iterator variable is a @MustCallAlias of the - // Iterable (such as an exceptional successor of hasNext() or next()), the checker cannot - // determine the iterator variable's must-call type. If iterator() terminates execution, - // then hasNext() and next() are unreachable, so no such merge occurs. - if (annotationProvider.getDeclAnnotation( - iteratorCallNode.getTarget().getMethod(), TerminatesExecution.class) - != null) { - extendWithMethodInvocationNode(iteratorCallNode); - } else { - extendWithNode(iteratorCallNode); - } + extendWithMethodInvocationNode(iteratorCallNode); translateAssignment( iteratorVariable, new LocalVariableNode(iteratorVariable), iteratorCallNode); From 8aa66f538e88a8b1ccc8e625898e753e298a5e3f Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 17 Nov 2026 06:43:49 -0800 Subject: [PATCH 32/98] Model suppressed close() exceptions on the exceptional path of a try-with-resources statement On the path on which the try block throws an exception, any exception that the desugared close() call throws is suppressed (JLS 14.20.3.1), so the primary exception propagates even if close() is @TerminatesExecution. --- .../cfg/builder/CFGTranslationPhaseOne.java | 38 ++++++++++++++++--- framework/tests/flow/Termination.java | 8 ++-- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index ba1c9e81a2bd..3d9c3518c99a 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2625,6 +2625,7 @@ public Node visitTry(TryTree tree, Void p) { finallyLabel, exceptionalFinallyLabel, () -> scan(finallyBlock, p), + () -> scan(finallyBlock, p), oldReturnTargetLC, oldBreakTargetLC, oldBreakLabels, @@ -2722,7 +2723,8 @@ private void handleTryResourcesAndBlock(TryTree tryTree, Void p, List addCloseCallForResource(resourceDeclarationTree, p), + () -> addCloseCallForResource(resourceDeclarationTree, p, false), + () -> addCloseCallForResource(resourceDeclarationTree, p, true), oldReturnTargetLC, oldBreakTargetLC, oldBreakLabels, @@ -2739,8 +2741,13 @@ private void handleTryResourcesAndBlock(TryTree tryTree, Void p, List oldBreakLabels, @@ -2872,7 +2900,7 @@ private void handleFinally( "start of finally block for Throwable #" + TreeUtils.treeUids.get(markerTree), env.getTypeUtils())); - finallyBlockCFGGenerator.run(); + exceptionalFinallyBlockCFGGenerator.run(); NodeWithExceptionsHolder throwing = extendWithNodeWithException( diff --git a/framework/tests/flow/Termination.java b/framework/tests/flow/Termination.java index 68239cd22756..a4104da47352 100644 --- a/framework/tests/flow/Termination.java +++ b/framework/tests/flow/Termination.java @@ -90,8 +90,9 @@ void t5(@Odd String p1, String p2, boolean b1, boolean b2) { @Odd String l3 = l1; } - // The desugared call to close() on the exceptional path terminates execution, so the catch - // clause is unreachable. + // The desugared call to close() terminates execution, but on the exceptional path, an exception + // that close() throws is suppressed and the primary exception propagates, so the catch clause is + // reachable. void t6(@Odd String p1, String p2, boolean b1) { String l1 = p2; if (b1) { @@ -104,10 +105,11 @@ void t6(@Odd String p1, String p2, boolean b1) { } catch (CheckedException e) { } } + // :: error: [assignment] @Odd String l3 = l1; } - // Like t6, but the desugared call to close() returns normally, so the catch clause is reachable. + // Like t6, but the desugared call to close() returns normally. void t6Returning(@Odd String p1, String p2, boolean b1) { String l1 = p2; if (b1) { From 44ca496d9dee3da02b1d39b77527481bc8fbae34 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 17 Nov 2026 06:45:34 -0800 Subject: [PATCH 33/98] Do not examine lambda and anonymous-class bodies when deciding whether arguments reassign the receiver Co-authored-by: Michael Ernst --- .../checker/nullness/NullnessTransfer.java | 20 ++++++++ .../ReceiverReassignedInArgument.java | 50 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 checker/tests/nullness/ReceiverReassignedInArgument.java diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index cc210db849a4..c2a8dbbd5559 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -1,8 +1,10 @@ package org.checkerframework.checker.nullness; import com.sun.source.tree.AssignmentTree; +import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; @@ -483,6 +485,11 @@ public TransferResult visitMethodInvocation( * #nonNullAssumptionAfterInvocation} is set) invokes a method or constructor that is not * side-effect-free. * + *

This method does not examine the bodies of lambda expressions and anonymous classes in the + * arguments. Evaluating the arguments executes such a body only through a method or constructor + * invocation (an anonymous class's initializers run as part of its constructor), which this + * method handles as described above. + * * @param arguments the arguments of a method invocation * @param receiverExpr the receiver of the method invocation * @return true if evaluating {@code arguments} might reassign {@code receiverExpr} @@ -535,6 +542,19 @@ public Boolean visitNewClass(NewClassTree tree, Void p) { || super.visitNewClass(tree, p); } + // visitMethodInvocation and visitNewClass handle the invocations that execute the body + // of a lambda expression or anonymous class. + + @Override + public Boolean visitLambdaExpression(LambdaExpressionTree tree, Void p) { + return false; + } + + @Override + public Boolean visitClass(ClassTree tree, Void p) { + return false; + } + /* * Returns true if assigning the given variable might reassign the receiver. * diff --git a/checker/tests/nullness/ReceiverReassignedInArgument.java b/checker/tests/nullness/ReceiverReassignedInArgument.java new file mode 100644 index 000000000000..7dccf51638f3 --- /dev/null +++ b/checker/tests/nullness/ReceiverReassignedInArgument.java @@ -0,0 +1,50 @@ +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.SideEffectFree; + +// A call's receiver is evaluated before its arguments. If an argument reassigns the receiver +// expression, then normal completion of the call does not show that the receiver expression is +// non-null afterward. ReceiverRefinementInCatch.java contains more such tests. +public class ReceiverReassignedInArgument { + + @Nullable ReceiverReassignedInArgument f; + + void take(@Nullable Object o) {} + + @SideEffectFree + void sefTake(@Nullable Object o) {} + + void assignInNestedArgument() { + ReceiverReassignedInArgument r = new ReceiverReassignedInArgument(); + r.take(String.valueOf(r = null)); + // :: error: (dereference.of.nullable) + r.toString(); + } + + // The argument assigns a non-null value to the receiver expression. + void assignNonNullInArgument(@Nullable Object r, Object nn) { + // :: error: (dereference.of.nullable) + r.equals(r = nn); + r.toString(); + } + + // Evaluating the argument does not execute the lambda body, and a side-effect-free method does + // not execute it either. + void assignInLambdaBody() { + // :: error: (dereference.of.nullable) + f.sefTake((Runnable) () -> f = null); + f.toString(); + } + + // Evaluating the argument executes the anonymous class's initializer. + void assignInAnonymousClassInitializer() { + // :: error: (dereference.of.nullable) + f.sefTake( + new Object() { + { + f = null; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } +} From 588281ab4c1fae925dade3794ddccf0482948870 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 17 Nov 2026 19:34:06 -0800 Subject: [PATCH 34/98] The exceptional path of a finally block rethrows the exceptions that reach it The end of the copy of a finally block for exceptions now throws each exception type that reaches the start of that copy, rather than Throwable. A client that ignores Throwable, such as the Resource Leak Checker, previously ignored every path on which an exception propagates out of a finally block. --- .../FinallyRethrowsException.java | 61 +++++++++++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 33 ++++++---- 2 files changed, 82 insertions(+), 12 deletions(-) create mode 100644 checker/tests/resourceleak/FinallyRethrowsException.java diff --git a/checker/tests/resourceleak/FinallyRethrowsException.java b/checker/tests/resourceleak/FinallyRethrowsException.java new file mode 100644 index 000000000000..d5410161b533 --- /dev/null +++ b/checker/tests/resourceleak/FinallyRethrowsException.java @@ -0,0 +1,61 @@ +// Tests that an exception that a finally block rethrows is not ignored. The exception is an +// IOException, which the Resource Leak Checker does not ignore. + +import java.io.*; +import org.checkerframework.checker.mustcall.qual.*; + +abstract class FinallyRethrowsException { + + public abstract @Owning Closeable alloc() throws IOException; + + public abstract void mightThrow() throws IOException; + + public abstract void log(); + + void leakAfterTryFinally() throws IOException { + // :: error: [required.method.not.called] + Closeable c = alloc(); + try { + mightThrow(); + } finally { + log(); + } + c.close(); + } + + void leakAfterNestedTryFinally() throws IOException { + // :: error: [required.method.not.called] + Closeable c = alloc(); + try { + try { + mightThrow(); + } finally { + log(); + } + } finally { + log(); + } + c.close(); + } + + void closedInFinally() throws IOException { + Closeable c = alloc(); + try { + mightThrow(); + } finally { + c.close(); + } + } + + void caughtBeforeFinally() throws IOException { + Closeable c = alloc(); + try { + mightThrow(); + } catch (IOException e) { + // The exception does not reach the finally block. + } finally { + log(); + } + c.close(); + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index ba1c9e81a2bd..1085a1774a82 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2860,11 +2860,15 @@ private void handleFinally( extendWithExtendedNode(new UnconditionalJump(doneLabel)); } - if (hasExceptionalPath(exceptionalFinallyLabel)) { + Set exceptionalFinallyCauses = exceptionsReaching(exceptionalFinallyLabel); + if (!exceptionalFinallyCauses.isEmpty()) { // If an exceptional path exists, scan 'finallyBlock' for 'exceptionalFinallyLabel', // and scan copied 'finallyBlock' for 'finallyLabel' (a successful path). If there // is no successful path, it will be removed in later phase. - // TODO: Don't we need a separate finally block for each kind of exception? + // After the finally block completes normally, it rethrows the exception that reached it, + // so the end of the finally block might throw each exception that reached its start. A + // single copy of the finally block serves all of those exceptions, so the analysis merges + // their stores within the finally block. addLabelForNextNode(exceptionalFinallyLabel); extendWithNode( new MarkerNode( @@ -2875,12 +2879,12 @@ private void handleFinally( finallyBlockCFGGenerator.run(); NodeWithExceptionsHolder throwing = - extendWithNodeWithException( + extendWithNodeWithExceptions( new MarkerNode( markerTree, "end of finally block for Throwable #" + TreeUtils.treeUids.get(markerTree), env.getTypeUtils()), - throwableType); + exceptionalFinallyCauses); throwing.setTerminatesExecution(true); } @@ -3006,22 +3010,27 @@ private void handleFinally( } /** - * Returns true if an exceptional node for {@code target} exists in {@link #nodeList}. + * Returns the types of the exceptions that a node in {@link #nodeList} throws to the given label, + * without duplicates. * - * @param target label for exception - * @return true when an exceptional node for {@code target} exists in {@link #nodeList} + * @param target a label, such as the entry of a finally block for exceptions + * @return the exception types, such as {@code java.io.IOException}, for which some node in {@link + * #nodeList} has an exceptional edge to {@code target}; empty if no node does */ - private boolean hasExceptionalPath(Label target) { + private Set exceptionsReaching(Label target) { + Set result = new ArraySet<>(); for (ExtendedNode node : nodeList) { if (node instanceof NodeWithExceptionsHolder exceptionalNode) { - for (Set

The types of the primary exception label exceptional edges of the call to the rethrow, in + * addition to the types of the exceptions that {@code close} might throw. So an analysis that + * ignores some exception types follows those edges, with the exceptional store of the call, + * whenever it follows the rethrow of the primary exception -- even if it ignores every exception + * that {@code close} might throw. Otherwise, if {@code close} terminates execution and might + * throw only ignored exceptions, the analysis would consider the rethrow of the primary exception + * unreachable. + * *

If {@code close} terminates execution, the call has no normal successor, but its exceptional * successors still reach the rethrow of the primary exception. That models termination by * throwing an exception. (If {@code close} terminates execution by exiting the JVM, the primary @@ -2894,16 +2920,18 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { * * @param resourceDeclarationTree the resource declaration, or the variable or field that is the * resource + * @param primaryExceptionTypes the types of the primary exception * @param p the value to pass to calls to {@code scan} */ - private void addSuppressingCloseCallForResource(Tree resourceDeclarationTree, Void p) { + private void addSuppressingCloseCallForResource( + Tree resourceDeclarationTree, Set primaryExceptionTypes, Void p) { Label suppressedLabel = new Label(); tryStack.pushFrame( new TryCatchFrame( types, Collections.singletonList( new TryCatchFrame.CatchLabel(throwableType, suppressedLabel)))); - addCloseCallForResource(resourceDeclarationTree, p); + addCloseCallForResource(resourceDeclarationTree, primaryExceptionTypes, p); tryStack.popFrame(); addLabelForNextNode(suppressedLabel); } @@ -2923,7 +2951,8 @@ private void addSuppressingCloseCallForResource(Tree resourceDeclarationTree, Vo * @param finallyBlockCFGGenerator generates CFG nodes and edges for the finally block, for each * path except the ones on which an exception reaches the finally block * @param exceptionalFinallyBlockCFGGenerator generates CFG nodes and edges for the finally block, - * for the paths on which an exception reaches the finally block + * for the paths on which an exception reaches the finally block; its argument is the types of + * the exceptions that reach the copy of the finally block and that the copy rethrows * @param oldReturnTargetLC old return target label cell, which gets restored to {@link * #returnTargetLC} while handling the finally block * @param oldBreakTargetLC old break target label cell, which gets restored to {@link @@ -2941,7 +2970,7 @@ private void handleFinally( Label finallyLabel, TryFinallyFrame exceptionalFinallyFrame, Runnable finallyBlockCFGGenerator, - Runnable exceptionalFinallyBlockCFGGenerator, + Consumer> exceptionalFinallyBlockCFGGenerator, LabelCell oldReturnTargetLC, LabelCell oldBreakTargetLC, Map oldBreakLabels, @@ -2988,7 +3017,7 @@ private void handleFinally( + TreeUtils.treeUids.get(markerTree), env.getTypeUtils())); - exceptionalFinallyBlockCFGGenerator.run(); + exceptionalFinallyBlockCFGGenerator.accept(group.keySet()); NodeWithExceptionsHolder throwing = extendWithNodeWithExceptions( @@ -3584,13 +3613,31 @@ private void extendWithMethodInvocationNode(MethodInvocationNode node) { * @param executable the method or constructor that {@code node} invokes */ private void extendWithInvocationNode(Node node, ExecutableElement executable) { + extendWithInvocationNode(node, executable, Collections.emptySet()); + } + + /** + * Extends the CFG with the given node, which invokes the given method or constructor, accounting + * for potential exceptions thrown by the invocation. If {@code executable} is annotated {@link + * TerminatesExecution}, the invocation terminates execution. + * + * @param node a method invocation or object creation + * @param executable the method or constructor that {@code node} invokes + * @param extraExceptionTypes types that label exceptional edges of {@code node}, in addition to + * the types of the exceptions that the invocation might throw + */ + private void extendWithInvocationNode( + Node node, ExecutableElement executable, Set extraExceptionTypes) { List thrownTypes = executable.getThrownTypes(); Set thrownSet = - ArraySet.newArraySetOrLinkedHashSet(thrownTypes.size() + uncheckedExceptionTypes.size()); + ArraySet.newArraySetOrLinkedHashSet( + thrownTypes.size() + uncheckedExceptionTypes.size() + extraExceptionTypes.size()); // Add exceptions explicitly mentioned in the throws clause. thrownSet.addAll(thrownTypes); // Add types to account for unchecked exceptions thrownSet.addAll(uncheckedExceptionTypes); + // Add the extra types that label exceptional edges. + thrownSet.addAll(extraExceptionTypes); ExtendedNode extendedNode = extendWithNodeWithExceptions(node, thrownSet); if (annotationProvider.getDeclAnnotation(executable, TerminatesExecution.class) != null) { From e042621c9704685e810882e09f709358efa2af8e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 19 Nov 2026 08:34:18 -0800 Subject: [PATCH 43/98] Fix the build after merging branch 'terminates-execution-check' --- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 516738f039a8..005d435bbfa7 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -3016,7 +3016,7 @@ private void handleFinally( + TreeUtils.treeUids.get(markerTree), env.getTypeUtils())); - exceptionalFinallyBlockCFGGenerator.accept(group.keySet()); + exceptionalFinallyBlockCFGGenerator.accept(Collections.singleton(exceptionType)); NodeWithExceptionsHolder throwing = extendWithNodeWithException( From 11f90e3c900919d5f205ecf30caa6a428d4e4eeb Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 19 Nov 2026 10:18:13 -0800 Subject: [PATCH 44/98] Share a finally copy among exception types that no method invocation throws A copy of a finally block for each exception type made the CFG of nested try-finally statements grow as 8^depth (a println throws 7 types), so :dataflow:cfgConstructionTest did not terminate. Now only a type that a method invocation throws gets its own copy, since only a method invocation can have a different exceptional store for each type; other types that the same nodes throw share a copy. ControlFlowGraph.checkInvariants computes each block's predecessors once, because doing so is quadratic in their number. --- .../dataflow/cfg/ControlFlowGraph.java | 8 +- .../cfg/builder/CFGTranslationPhaseOne.java | 99 +++++++++++++++---- .../dataflow/cfg/builder/TryFinallyFrame.java | 11 ++- 3 files changed, 97 insertions(+), 21 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java index f4eded2d6802..a19d6097bc41 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java @@ -151,6 +151,10 @@ public ControlFlowGraph( */ public void checkInvariants() { // TODO: this is a big data structure with many more invariants... + // The predecessors of each block, computed once per block. Block.getPredecessors takes time + // quadratic in the number of predecessors, and a block such as the exceptional exit can have + // thousands of predecessors. + IdentityHashMap> predecessors = new IdentityHashMap<>(); for (Block b : getAllBlocks()) { // Each node in the block should have this block as its parent. @@ -168,7 +172,9 @@ public void checkInvariants() { // Each successor should have this block in its predecessors. for (Block succ : b.getSuccessors()) { - if (!succ.getPredecessors().contains(b)) { + if (!predecessors + .computeIfAbsent(succ, s -> new HashSet<>(s.getPredecessors())) + .contains(b)) { throw new IllegalStateException( "Block " + b diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 19702bdc6e8b..fa567905ff23 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2575,7 +2575,7 @@ public Node visitTry(TryTree tree, Void p) { if (finallyBlock != null) { finallyLabel = new Label(); - exceptionalFinallyFrame = new TryFinallyFrame(types); + exceptionalFinallyFrame = new TryFinallyFrame(types, nodeList.size()); tryStack.pushFrame(exceptionalFinallyFrame); returnTargetLC = new LabelCell(); @@ -2690,7 +2690,7 @@ private void handleTryResourcesAndBlock(TryTree tryTree, Void p, List entry : - exceptionalFinallyFrame.getExceptionLabels().entrySet()) { - TypeMirror exceptionType = entry.getKey(); - addLabelForNextNode(entry.getValue()); + // For each exception that reaches the finally block, there is a copy of the finally block that + // rethrows that exception after the finally block completes normally. If two exceptions + // shared a copy, the analysis would merge the stores of the paths that throw them, and the end + // of the copy would rethrow each exception with the merged store. For example, an exception + // thrown while a resource is open would make the Resource Leak Checker report a leak on the + // path of another exception that is thrown after the resource is closed. So exceptions that + // different nodes throw get different copies. A transfer function can give a method + // invocation a different exceptional store for each type that it throws, as for a method + // annotated with @EnsuresCalledMethodsOnException, so each type that a method invocation + // throws gets its own copy. Other exceptions that the same nodes throw share a copy: a copy + // for each type would make the size of the CFG exponential, with a large base, in the depth of + // the nesting of finally blocks. + for (Map group : exceptionGroups(exceptionalFinallyFrame)) { + for (Label label : group.values()) { + addLabelForNextNode(label); + } + String exceptionsString = group.keySet().toString(); extendWithNode( new MarkerNode( markerTree, "start of finally block for " - + exceptionType + + exceptionsString + " #" + TreeUtils.treeUids.get(markerTree), env.getTypeUtils())); @@ -2886,15 +2890,15 @@ private void handleFinally( finallyBlockCFGGenerator.run(); NodeWithExceptionsHolder throwing = - extendWithNodeWithException( + extendWithNodeWithExceptions( new MarkerNode( markerTree, "end of finally block for " - + exceptionType + + exceptionsString + " #" + TreeUtils.treeUids.get(markerTree), env.getTypeUtils()), - exceptionType); + Collections.unmodifiableSet(group.keySet())); throwing.setTerminatesExecution(true); } @@ -3019,6 +3023,63 @@ private void handleFinally( } } + /** + * Returns the types of the exceptions that reach the given frame, grouped by the nodes that throw + * them. A type that a method invocation throws to the frame is alone in its group. Two other + * types are in the same group if and only if the same nodes throw them to the frame. + * + * @param frame a frame for a finally block, which the CFG builder has popped from the try stack + * @return the groups, in the order that their first types reach {@code frame}; each group maps + * each of its types to the type's label in {@code frame}. Empty if no exception reaches + * {@code frame}. + */ + private List> exceptionGroups(TryFinallyFrame frame) { + Map exceptionLabels = frame.getExceptionLabels(); + if (exceptionLabels.isEmpty()) { + return Collections.emptyList(); + } + Set

The call follows those edges whenever {@code close} throws an exception, whatever its type, + * so the call records their types (see {@link MethodInvocationNode#getAnyExceptionTypes()}). An + * analysis must not apply, on those edges, a fact that holds only when {@code close} throws an + * exception of a particular type, such as an exceptional postcondition of {@code close}. The + * normal successor of the call, if any, is unaffected. + * *

If {@code close} terminates execution, the call has no normal successor, but its exceptional * successors still reach the rethrow of the primary exception. That models termination by * throwing an exception. (If {@code close} terminates execution by exiting the JVM, the primary diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java index 7e7fc1af204b..9d49096aab7c 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java @@ -7,9 +7,12 @@ import com.sun.source.util.TreePath; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; +import java.util.Set; +import javax.lang.model.type.TypeMirror; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.javacutil.TreeUtils; @@ -60,6 +63,21 @@ public class MethodInvocationNode extends Node { */ protected @Nullable EnhancedForLoopTree enhancedForLoop; + /** + * Types that label exceptional edges of this invocation that it follows whenever it throws an + * exception, regardless of the type of the exception that it throws. Usually empty. + * + *

If this MethodInvocationNode is a synthetic {@code close()} call on a path on which a + * try-with-resources statement suppresses any exception that {@code close()} throws and then + * rethrows the primary exception, then these are the types of the primary exception. + * + *

A fact that holds only when the invoked method throws an exception of a particular type, + * such as an exceptional postcondition, does not hold on an edge labeled by one of these types. + * + *

Is set by {@link #setAnyExceptionTypes}. + */ + protected Set anyExceptionTypes = Collections.emptySet(); + /** * Creates a MethodInvocationNode. * @@ -144,6 +162,33 @@ public void setEnhancedForLoop(@Nullable EnhancedForLoopTree enhancedForLoop) { this.enhancedForLoop = enhancedForLoop; } + /** + * Returns the types that label exceptional edges of this invocation that it follows whenever it + * throws an exception, regardless of the type of the exception that it throws. Usually empty. + * + *

A fact that holds only when the invoked method throws an exception of a particular type, + * such as an exceptional postcondition, does not hold on an edge labeled by one of these types. + * + * @return the types that label exceptional edges that this invocation follows whenever it throws + * an exception + * @see #anyExceptionTypes + */ + public Set getAnyExceptionTypes() { + return anyExceptionTypes; + } + + /** + * Sets the types that label exceptional edges of this invocation that it follows whenever it + * throws an exception, regardless of the type of the exception that it throws. + * + * @param anyExceptionTypes the types that label exceptional edges that this invocation follows + * whenever it throws an exception + * @see #getAnyExceptionTypes() + */ + public void setAnyExceptionTypes(Set anyExceptionTypes) { + this.anyExceptionTypes = anyExceptionTypes; + } + @Override public @Nullable MethodInvocationTree getTree() { return tree; From 92bbac3a72e2bc3816addd48f73741fada4f630e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 18:47:05 -0800 Subject: [PATCH 52/98] Model the call to addSuppressed in a try-with-resources, which may throw IllegalArgumentException --- .../cfg/builder/CFGTranslationPhaseOne.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 5f88c1ea7fc5..c4fd018a6318 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -345,6 +345,9 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** The ClassCastException type. */ protected final TypeMirror classCastExceptionType; + /** The IllegalArgumentException type. */ + protected final TypeMirror illegalArgumentExceptionType; + /** The Iterable type (erased). */ protected final TypeMirror iterableType; @@ -441,6 +444,7 @@ public CFGTranslationPhaseOne( arrayIndexOutOfBoundsExceptionType = getTypeMirror(ArrayIndexOutOfBoundsException.class); assertionErrorType = getTypeMirror(AssertionError.class); classCastExceptionType = getTypeMirror(ClassCastException.class); + illegalArgumentExceptionType = getTypeMirror(IllegalArgumentException.class); iterableType = types.erasure(getTypeMirror(Iterable.class)); negativeArraySizeExceptionType = getTypeMirror(NegativeArraySizeException.class); nullPointerExceptionType = getTypeMirror(NullPointerException.class); @@ -2814,8 +2818,11 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { * Adds a synthetic {@code close} call to the CFG, as {@link #addCloseCallForResource} does, for * the path on which an exception (the primary exception) reached the synthetic finally block of a * try-with-resources statement. On that path, the statement suppresses any exception that {@code - * close} throws, and then it rethrows the primary exception (JLS 14.20.3.1). So every exceptional - * successor of the added nodes is the node that follows them. + * close} throws, by calling {@code addSuppressed} on the primary exception, and then it rethrows + * the primary exception (JLS 14.20.3.1). So every exceptional successor of the {@code close} call + * is a node that models the call to {@code addSuppressed}. That node may throw {@code + * IllegalArgumentException}, which {@code addSuppressed} throws if {@code close} threw the + * primary exception itself; otherwise it reaches the rethrow of the primary exception. * *

If {@code close} terminates execution, the call has no normal successor, but its exceptional * successors still reach the rethrow of the primary exception. That models termination by @@ -2835,7 +2842,20 @@ private void addSuppressingCloseCallForResource(Tree resourceDeclarationTree, Vo new TryCatchFrame.CatchLabel(throwableType, suppressedLabel)))); addCloseCallForResource(resourceDeclarationTree, p); tryStack.popFrame(); + Label afterSuppressionLabel = new Label(); + extendWithExtendedNode(new UnconditionalJump(afterSuppressionLabel)); + + // The catch block calls addSuppressed on the primary exception, which throws + // IllegalArgumentException if close threw the primary exception itself. addLabelForNextNode(suppressedLabel); + extendWithNodeWithException( + new MarkerNode( + resourceDeclarationTree, + "addSuppressed for resource #" + TreeUtils.treeUids.get(resourceDeclarationTree), + env.getTypeUtils()), + illegalArgumentExceptionType); + + addLabelForNextNode(afterSuppressionLabel); } /** From 0c824e9dad98fbc52f0d0c79fbd6123e8c7e9c24 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 18 Nov 2026 23:08:47 -0800 Subject: [PATCH 53/98] Keep the primary exception reachable when a suppressed close() throws only ignored exceptions On the path on which a try-with-resources statement suppresses an exception from close() and rethrows the primary exception, the types of the primary exception also label the close() call's exceptional edges. So an analysis that ignores some exception types, such as the Resource Leak Checker, follows the suppression continuation whenever it follows the rethrow, even if close() terminates execution and throws only ignored exceptions. --- .../TryWithResourcesPrimaryException.java | 22 +++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 65 ++++++++++++++++--- 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/checker/tests/resourceleak/TryWithResourcesPrimaryException.java b/checker/tests/resourceleak/TryWithResourcesPrimaryException.java index 1257002a5e72..c9489f1505ae 100644 --- a/checker/tests/resourceleak/TryWithResourcesPrimaryException.java +++ b/checker/tests/resourceleak/TryWithResourcesPrimaryException.java @@ -5,6 +5,7 @@ import java.io.*; import org.checkerframework.checker.mustcall.qual.*; +import org.checkerframework.dataflow.qual.TerminatesExecution; abstract class TryWithResourcesPrimaryException { @@ -31,4 +32,25 @@ void closedInTryBlock() throws IOException { mightThrow(); } } + + // A resource whose close() terminates execution by throwing an Error, which the Resource Leak + // Checker ignores. The try-with-resources statement suppresses that Error and rethrows the + // primary exception. + static class TerminatingClose implements Closeable { + @Override + @TerminatesExecution + public void close() { + throw new Error(); + } + } + + void leakWhenTryBlockThrowsAndCloseTerminates() throws IOException { + // :: error: [required.method.not.called] + Closeable c = alloc(); + try (TerminatingClose r = new TerminatingClose()) { + // If mightThrow() throws, c is not closed. + mightThrow(); + c.close(); + } + } } diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index c4fd018a6318..32c266aa0331 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -72,6 +72,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; @@ -2631,7 +2632,7 @@ public Node visitTry(TryTree tree, Void p) { finallyLabel, exceptionalFinallyFrame, () -> scan(finallyBlock, p), - () -> scan(finallyBlock, p), + primaryExceptionTypes -> scan(finallyBlock, p), oldReturnTargetLC, oldBreakTargetLC, oldBreakLabels, @@ -2730,7 +2731,8 @@ private void handleTryResourcesAndBlock(TryTree tryTree, Void p, List addCloseCallForResource(resourceDeclarationTree, p), - () -> addSuppressingCloseCallForResource(resourceDeclarationTree, p), + primaryExceptionTypes -> + addSuppressingCloseCallForResource(resourceDeclarationTree, primaryExceptionTypes, p), oldReturnTargetLC, oldBreakTargetLC, oldBreakLabels, @@ -2749,6 +2751,21 @@ private void handleTryResourcesAndBlock(TryTree tryTree, Void p, List extraExceptionTypes, Void p) { // The receiver of close() is a use of the resource variable or field. Tree receiverTree; Node receiverNode; @@ -2807,7 +2824,8 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { new MethodInvocationNode( closeCall, closeAccessNode, Collections.emptyList(), getCurrentPath()); closeCallNode.setInSource(false); - extendWithMethodInvocationNode(closeCallNode); + extendWithInvocationNode( + closeCallNode, closeCallNode.getTarget().getMethod(), extraExceptionTypes); if (resourceMayBeNull) { addLabelForNextNode(afterCloseLabel); @@ -2824,6 +2842,14 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { * IllegalArgumentException}, which {@code addSuppressed} throws if {@code close} threw the * primary exception itself; otherwise it reaches the rethrow of the primary exception. * + *

The types of the primary exception label exceptional edges of the call to the rethrow, in + * addition to the types of the exceptions that {@code close} might throw. So an analysis that + * ignores some exception types follows those edges, with the exceptional store of the call, + * whenever it follows the rethrow of the primary exception -- even if it ignores every exception + * that {@code close} might throw. Otherwise, if {@code close} terminates execution and might + * throw only ignored exceptions, the analysis would consider the rethrow of the primary exception + * unreachable. + * *

If {@code close} terminates execution, the call has no normal successor, but its exceptional * successors still reach the rethrow of the primary exception. That models termination by * throwing an exception. (If {@code close} terminates execution by exiting the JVM, the primary @@ -2831,16 +2857,18 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { * * @param resourceDeclarationTree the resource declaration, or the variable or field that is the * resource + * @param primaryExceptionTypes the types of the primary exception * @param p the value to pass to calls to {@code scan} */ - private void addSuppressingCloseCallForResource(Tree resourceDeclarationTree, Void p) { + private void addSuppressingCloseCallForResource( + Tree resourceDeclarationTree, Set primaryExceptionTypes, Void p) { Label suppressedLabel = new Label(); tryStack.pushFrame( new TryCatchFrame( types, Collections.singletonList( new TryCatchFrame.CatchLabel(throwableType, suppressedLabel)))); - addCloseCallForResource(resourceDeclarationTree, p); + addCloseCallForResource(resourceDeclarationTree, primaryExceptionTypes, p); tryStack.popFrame(); Label afterSuppressionLabel = new Label(); extendWithExtendedNode(new UnconditionalJump(afterSuppressionLabel)); @@ -2873,7 +2901,8 @@ private void addSuppressingCloseCallForResource(Tree resourceDeclarationTree, Vo * @param finallyBlockCFGGenerator generates CFG nodes and edges for the finally block, for each * path except the ones on which an exception reaches the finally block * @param exceptionalFinallyBlockCFGGenerator generates CFG nodes and edges for the finally block, - * for the paths on which an exception reaches the finally block + * for the paths on which an exception reaches the finally block; its argument is the types of + * the exceptions that reach the copy of the finally block and that the copy rethrows * @param oldReturnTargetLC old return target label cell, which gets restored to {@link * #returnTargetLC} while handling the finally block * @param oldBreakTargetLC old break target label cell, which gets restored to {@link @@ -2891,7 +2920,7 @@ private void handleFinally( Label finallyLabel, TryFinallyFrame exceptionalFinallyFrame, Runnable finallyBlockCFGGenerator, - Runnable exceptionalFinallyBlockCFGGenerator, + Consumer> exceptionalFinallyBlockCFGGenerator, LabelCell oldReturnTargetLC, LabelCell oldBreakTargetLC, Map oldBreakLabels, @@ -2943,7 +2972,7 @@ private void handleFinally( + TreeUtils.treeUids.get(markerTree), env.getTypeUtils())); - exceptionalFinallyBlockCFGGenerator.run(); + exceptionalFinallyBlockCFGGenerator.accept(group.keySet()); NodeWithExceptionsHolder throwing = extendWithNodeWithExceptions( @@ -3526,13 +3555,31 @@ private void extendWithMethodInvocationNode(MethodInvocationNode node) { * @param executable the method or constructor that {@code node} invokes */ private void extendWithInvocationNode(Node node, ExecutableElement executable) { + extendWithInvocationNode(node, executable, Collections.emptySet()); + } + + /** + * Extends the CFG with the given node, which invokes the given method or constructor, accounting + * for potential exceptions thrown by the invocation. If {@code executable} is annotated {@link + * TerminatesExecution}, the invocation terminates execution. + * + * @param node a method invocation or object creation + * @param executable the method or constructor that {@code node} invokes + * @param extraExceptionTypes types that label exceptional edges of {@code node}, in addition to + * the types of the exceptions that the invocation might throw + */ + private void extendWithInvocationNode( + Node node, ExecutableElement executable, Set extraExceptionTypes) { List thrownTypes = executable.getThrownTypes(); Set thrownSet = - ArraySet.newArraySetOrLinkedHashSet(thrownTypes.size() + uncheckedExceptionTypes.size()); + ArraySet.newArraySetOrLinkedHashSet( + thrownTypes.size() + uncheckedExceptionTypes.size() + extraExceptionTypes.size()); // Add exceptions explicitly mentioned in the throws clause. thrownSet.addAll(thrownTypes); // Add types to account for unchecked exceptions thrownSet.addAll(uncheckedExceptionTypes); + // Add the extra types that label exceptional edges. + thrownSet.addAll(extraExceptionTypes); ExtendedNode extendedNode = extendWithNodeWithExceptions(node, thrownSet); if (annotationProvider.getDeclAnnotation(executable, TerminatesExecution.class) != null) { From 16d2f14ddfc6eff6b75b0a7b6f0d7278a7f4ffea Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 18:00:16 -0800 Subject: [PATCH 54/98] Do not apply exceptional postconditions of a suppressed close() on the primary-exception edges The edges of a suppressed close() call that are labeled by the types of the primary exception are followed whenever close() throws, even if it throws an Error. MethodInvocationNode now records those types, and CalledMethodsTransfer does not apply @EnsuresCalledMethodsOnException facts on edges labeled by them. --- .../calledmethods/CalledMethodsTransfer.java | 10 ++++- .../TryWithResourcesPrimaryException.java | 25 +++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 11 ++++- .../cfg/node/MethodInvocationNode.java | 45 +++++++++++++++++++ 4 files changed, 88 insertions(+), 3 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/calledmethods/CalledMethodsTransfer.java b/checker/src/main/java/org/checkerframework/checker/calledmethods/CalledMethodsTransfer.java index 6e0ab178cbb2..619861deef89 100644 --- a/checker/src/main/java/org/checkerframework/checker/calledmethods/CalledMethodsTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/calledmethods/CalledMethodsTransfer.java @@ -261,7 +261,8 @@ private void handleEnsuresCalledMethodsVarargs( /** * Update the given {@code exceptionalStores} for the {@link * org.checkerframework.checker.calledmethods.qual.EnsuresCalledMethodsOnException} annotations - * written on the given {@code method}. + * written on the given {@code method}. Does not update the store for an exception type in {@link + * MethodInvocationNode#getAnyExceptionTypes()}. * * @param node a method invocation * @param method the method being invoked @@ -302,7 +303,12 @@ private void handleEnsuresCalledMethodsOnException( AnnotationMirror calledMethod = atypeFactory.createAccumulatorAnnotation(postcond.method()); for (Map.Entry successor : exceptionalStores.entrySet()) { TypeMirror caughtException = successor.getKey(); - if (types.isSubtype(caughtException, javaLangExceptionType)) { + // The invocation follows an edge labeled by one of node.getAnyExceptionTypes() whenever it + // throws an exception, even one that is not an Exception, so the postcondition might not + // hold on that edge. + if (types.isSubtype(caughtException, javaLangExceptionType) + && node.getAnyExceptionTypes().stream() + .noneMatch(t -> types.isSameType(t, caughtException))) { AccumulationStore resultStore = successor.getValue(); resultStore.insertOrRefine(e, calledMethod); } diff --git a/checker/tests/resourceleak/TryWithResourcesPrimaryException.java b/checker/tests/resourceleak/TryWithResourcesPrimaryException.java index c9489f1505ae..05a169ce55ae 100644 --- a/checker/tests/resourceleak/TryWithResourcesPrimaryException.java +++ b/checker/tests/resourceleak/TryWithResourcesPrimaryException.java @@ -4,6 +4,7 @@ // does not ignore. import java.io.*; +import org.checkerframework.checker.calledmethods.qual.EnsuresCalledMethodsOnException; import org.checkerframework.checker.mustcall.qual.*; import org.checkerframework.dataflow.qual.TerminatesExecution; @@ -53,4 +54,28 @@ void leakWhenTryBlockThrowsAndCloseTerminates() throws IOException { c.close(); } } + + // A resource whose close() promises to call finish() if close() throws an Exception, but which + // terminates execution by throwing an Error without calling finish(). + @InheritableMustCall({"close", "finish"}) + abstract static class FinishingTerminatingClose implements Closeable { + abstract void finish(); + + @Override + @TerminatesExecution + @EnsuresCalledMethodsOnException(value = "this", methods = "finish") + public abstract void close(); + } + + abstract @Owning FinishingTerminatingClose allocFinishing(); + + void finishNotCalledWhenTryBlockThrowsAndCloseTerminates() throws IOException { + // If mightThrow() throws an IOException, then close() throws an Error without calling + // finish(), and the try-with-resources statement rethrows the IOException. + // :: error: [required.method.not.called] + try (FinishingTerminatingClose r = allocFinishing()) { + mightThrow(); + r.finish(); + } + } } diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 32c266aa0331..be6b308cb5f7 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2761,7 +2761,9 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { * @param resourceDeclarationTree the resource declaration, or the variable or field that is the * resource * @param extraExceptionTypes types that label exceptional edges of the {@code close} call, in - * addition to the types of the exceptions that the call might throw + * addition to the types of the exceptions that the call might throw; the call follows those + * edges whenever it throws an exception (see {@link + * MethodInvocationNode#getAnyExceptionTypes()}) * @param p the value to pass to calls to {@code scan} */ private void addCloseCallForResource( @@ -2824,6 +2826,7 @@ private void addCloseCallForResource( new MethodInvocationNode( closeCall, closeAccessNode, Collections.emptyList(), getCurrentPath()); closeCallNode.setInSource(false); + closeCallNode.setAnyExceptionTypes(extraExceptionTypes); extendWithInvocationNode( closeCallNode, closeCallNode.getTarget().getMethod(), extraExceptionTypes); @@ -2850,6 +2853,12 @@ private void addCloseCallForResource( * throw only ignored exceptions, the analysis would consider the rethrow of the primary exception * unreachable. * + *

The call follows those edges whenever {@code close} throws an exception, whatever its type, + * so the call records their types (see {@link MethodInvocationNode#getAnyExceptionTypes()}). An + * analysis must not apply, on those edges, a fact that holds only when {@code close} throws an + * exception of a particular type, such as an exceptional postcondition of {@code close}. The + * normal successor of the call, if any, is unaffected. + * *

If {@code close} terminates execution, the call has no normal successor, but its exceptional * successors still reach the rethrow of the primary exception. That models termination by * throwing an exception. (If {@code close} terminates execution by exiting the JVM, the primary diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java index 7e7fc1af204b..9d49096aab7c 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/MethodInvocationNode.java @@ -7,9 +7,12 @@ import com.sun.source.util.TreePath; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; +import java.util.Set; +import javax.lang.model.type.TypeMirror; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.javacutil.TreeUtils; @@ -60,6 +63,21 @@ public class MethodInvocationNode extends Node { */ protected @Nullable EnhancedForLoopTree enhancedForLoop; + /** + * Types that label exceptional edges of this invocation that it follows whenever it throws an + * exception, regardless of the type of the exception that it throws. Usually empty. + * + *

If this MethodInvocationNode is a synthetic {@code close()} call on a path on which a + * try-with-resources statement suppresses any exception that {@code close()} throws and then + * rethrows the primary exception, then these are the types of the primary exception. + * + *

A fact that holds only when the invoked method throws an exception of a particular type, + * such as an exceptional postcondition, does not hold on an edge labeled by one of these types. + * + *

Is set by {@link #setAnyExceptionTypes}. + */ + protected Set anyExceptionTypes = Collections.emptySet(); + /** * Creates a MethodInvocationNode. * @@ -144,6 +162,33 @@ public void setEnhancedForLoop(@Nullable EnhancedForLoopTree enhancedForLoop) { this.enhancedForLoop = enhancedForLoop; } + /** + * Returns the types that label exceptional edges of this invocation that it follows whenever it + * throws an exception, regardless of the type of the exception that it throws. Usually empty. + * + *

A fact that holds only when the invoked method throws an exception of a particular type, + * such as an exceptional postcondition, does not hold on an edge labeled by one of these types. + * + * @return the types that label exceptional edges that this invocation follows whenever it throws + * an exception + * @see #anyExceptionTypes + */ + public Set getAnyExceptionTypes() { + return anyExceptionTypes; + } + + /** + * Sets the types that label exceptional edges of this invocation that it follows whenever it + * throws an exception, regardless of the type of the exception that it throws. + * + * @param anyExceptionTypes the types that label exceptional edges that this invocation follows + * whenever it throws an exception + * @see #getAnyExceptionTypes() + */ + public void setAnyExceptionTypes(Set anyExceptionTypes) { + this.anyExceptionTypes = anyExceptionTypes; + } + @Override public @Nullable MethodInvocationTree getTree() { return tree; From fa0c94e3237e1fabc4cf0cc8bbd9208b98b8afa1 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 20:31:01 -0800 Subject: [PATCH 55/98] Bound the extra exceptional copies of nested finally blocks --- .../cfg/builder/CFGTranslationPhaseOne.java | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 122f727f19be..cbe07c53cda7 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -286,6 +286,19 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** SwitchBuilder for the current switch. Used to match yield statements to enclosing switches. */ private SwitchBuilder switchBuilder; + /** + * The maximum number of nodes in extra exceptional copies of finally blocks, beyond which the + * exceptions that reach a finally block share one copy. An extra copy is one other than the first + * exceptional copy of a given finally block. See {@link #handleFinally}. + */ + private static final int EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET = 10_000; + + /** + * The number of nodes in extra exceptional copies of finally blocks so far. Nodes in nested extra + * copies are counted more than once. + */ + private int extraExceptionalFinallyNodes = 0; + /** * Maps from AST {@link Tree}s to sets of {@link Node}s. Every Tree that produces a value will * have at least one corresponding Node. Trees that undergo implicit conversions, such as boxing @@ -2875,7 +2888,26 @@ private void handleFinally( // the analysis merges their stores there anyway. The number of copies grows exponentially with // the depth of the nesting of finally blocks in finally blocks, with a base that grows with the // number of copies per finally block. A copy for each type would make the base much larger. - for (Map group : exceptionGroups(exceptionalFinallyFrame)) { + // To bound that growth, once the copies beyond the first copy for each finally block have + // contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the remaining groups of each + // finally block share a single copy, which rethrows each of their exceptions. + List> groups = new ArrayList<>(exceptionGroups(exceptionalFinallyFrame)); + for (int i = 0; i < groups.size(); i++) { + Map group = groups.get(i); + boolean isExtraCopy = i > 0; + if (isExtraCopy + && extraExceptionalFinallyNodes >= EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET + && i < groups.size() - 1) { + Map sharedGroup = new ArrayMap<>(); + for (Map remainingGroup : groups.subList(i, groups.size())) { + sharedGroup.putAll(remainingGroup); + } + groups.subList(i, groups.size()).clear(); + groups.add(sharedGroup); + group = sharedGroup; + } + int sizeBeforeCopy = nodeList.size(); + for (Label label : group.values()) { addLabelForNextNode(label); } @@ -2903,6 +2935,11 @@ private void handleFinally( Collections.unmodifiableSet(group.keySet())); throwing.setTerminatesExecution(true); + + if (isExtraCopy) { + // This overcounts the nodes of a nested extra copy, which is conservative. + extraExceptionalFinallyNodes += nodeList.size() - sizeBeforeCopy; + } } if (returnTargetLC.wasAccessed()) { From 83fceef5932f785db3e0c436301e25dc7e28b59d Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 20:38:05 -0800 Subject: [PATCH 56/98] Update the busy-expression test's expected output: the method access follows the arguments --- dataflow/tests/busyexpr/Expected.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dataflow/tests/busyexpr/Expected.txt b/dataflow/tests/busyexpr/Expected.txt index 3afba5abbe68..554005471ed0 100644 --- a/dataflow/tests/busyexpr/Expected.txt +++ b/dataflow/tests/busyexpr/Expected.txt @@ -94,10 +94,10 @@ a [ LocalVariable ] a = 0 [ Assignment ] expression statement a = 0 [ ExpressionStatement ] (this) [ ImplicitThis ] -(this).test [ MethodAccess ] a [ LocalVariable ] b [ LocalVariable ] (a - b) [ NumericalSubtraction ] +(this).test [ MethodAccess ] ~~~~~~~~~ TransferInput#39 After: busy expressions = (a - b) From 98ab8c974664cc9a8aa77418f71e1eff8d6586c7 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 20:38:06 -0800 Subject: [PATCH 57/98] Refine receivers and arguments more carefully after a call - Do not refine an argument that a later argument might reassign, as in `m(x, x = null)`. - A receiver that contains a method call might change when an argument writes a non-local variable or calls a method that has side effects. - An annotation in an argument is not evaluated, so its element-value pairs do not reassign anything. - Matching a record pattern in an argument invokes the record's component accessors, which might reassign the receiver. - Honor @DoesNotUnrefineReceiver when refining a receiver after a call. - Refine the receiver on the exceptional successors of a call whose type excludes NullPointerException, such as a handler for a checked exception. --- .../checker/nullness/NullnessTransfer.java | 173 ++++++++++++++++-- .../ReceiverDependsOnStaticField.java | 28 +++ .../ReceiverReassignedInArgument.java | 74 +++++++- .../nullness/ReceiverRefinementInCatch.java | 35 ++++ .../ReceiverReassignedInRecordPattern.java | 49 +++++ .../flow/ReceiverNullPointerException.java | 12 ++ 6 files changed, 350 insertions(+), 21 deletions(-) create mode 100644 checker/tests/nullness/ReceiverDependsOnStaticField.java create mode 100644 checker/tests/nullness/java21/ReceiverReassignedInRecordPattern.java diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 3d864ac59f0f..cbed0489a6fb 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -1,5 +1,6 @@ package org.checkerframework.checker.nullness; +import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; @@ -8,12 +9,16 @@ import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.util.TreeScanner; +import java.util.HashMap; import java.util.List; import java.util.Map; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.RecordComponentElement; +import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; @@ -26,6 +31,7 @@ import org.checkerframework.dataflow.analysis.ConditionalTransferResult; import org.checkerframework.dataflow.analysis.TransferInput; import org.checkerframework.dataflow.analysis.TransferResult; +import org.checkerframework.dataflow.cfg.block.ExceptionBlock; import org.checkerframework.dataflow.cfg.node.ArrayAccessNode; import org.checkerframework.dataflow.cfg.node.FieldAccessNode; import org.checkerframework.dataflow.cfg.node.InstanceOfNode; @@ -36,6 +42,7 @@ import org.checkerframework.dataflow.cfg.node.ThrowNode; import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.dataflow.expression.LocalVariable; +import org.checkerframework.dataflow.expression.MethodCall; import org.checkerframework.framework.flow.CFAbstractStore; import org.checkerframework.framework.type.AnnotatedTypeMirror; import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType; @@ -101,6 +108,9 @@ public class NullnessTransfer */ private final boolean nonNullAssumptionAfterInvocation; + /** The type {@code java.lang.NullPointerException}. */ + private final TypeMirror nullPointerExceptionType; + /** * Create a new NullnessTransfer for the given analysis. * @@ -137,6 +147,9 @@ public NullnessTransfer(NullnessAnalysis analysis) { .getTypeFactory() .getChecker() .getBooleanOption("invocationPreservesArgumentNullness", true); + + nullPointerExceptionType = + TypesUtils.typeFromClass(NullPointerException.class, analysis.getTypes(), elements); } /** @@ -397,7 +410,9 @@ public TransferResult visitThrow( * *

When the flag is turned off, the analysis is sound: it checks that the method is * SideEffectFree or the receiver is unassignable. Only if either one of the two is true is the - * receiver made non-null. Similar logic is applied to the arguments of the invocation. + * receiver made non-null. The receiver is also made non-null if the method is annotated {@link + * org.checkerframework.framework.qual.DoesNotUnrefineReceiver}. Similar logic is applied to the + * arguments of the invocation. * *

The receiver of a static method invocation is never made non-null, because the invocation * does not dereference it. @@ -412,8 +427,6 @@ public TransferResult visitThrow( @Override public TransferResult visitMethodInvocation( MethodInvocationNode n, TransferInput in) { - TransferResult result = super.visitMethodInvocation(n, in); - MethodInvocationTree tree = n.getTree(); ExecutableElement method = n.getTarget().getMethod(); @@ -428,30 +441,52 @@ public TransferResult visitMethodInvocation( // before the arguments, so it is skipped if evaluating the arguments might reassign the // receiver expression, as in `r.m(r = null)`. It is also skipped for a synthetic invocation // that has no tree, whose arguments cannot be examined. + // A method annotated @DoesNotUnrefineReceiver does not reassign its receiver expression. JavaExpression receiverExpr = JavaExpression.fromNode(receiver); - if (!n.getTarget().isStatic() - && (nonNullAssumptionAfterInvocation - || isMethodSideEffectFree - || !receiverExpr.isAssignableByOtherCode()) - && tree != null - && !argumentsMayReassign(tree.getArguments(), receiverExpr)) { + boolean refineReceiver = + !n.getTarget().isStatic() + && (nonNullAssumptionAfterInvocation + || isMethodSideEffectFree + || atypeFactory.hasDoesNotUnrefineReceiver(method) + || !receiverExpr.isAssignableByOtherCode()) + && tree != null + && !argumentsMayReassign(tree.getArguments(), receiverExpr); + + // The exceptional successors of the invocation get the store before the invocation, which + // super.visitMethodInvocation modifies in place. So, copy it first. + @Nullable NullnessStore storeBeforeInvocation = + refineReceiver && n.getBlock() instanceof ExceptionBlock + ? in.getRegularStore().copy() + : null; + + TransferResult result = super.visitMethodInvocation(n, in); + + if (refineReceiver) { // Make receiver non-null. makeNonNull(result, receiver); + if (storeBeforeInvocation != null) { + result = refineReceiverOnExceptionalSuccessors(n, result, storeBeforeInvocation); + } } // For all formal parameters with a non-null annotation, make the actual argument non-null. // The point of this is to prevent cascaded errors -- the Nullness Checker will issue a // warning for the method invocation, but not for subsequent uses of the argument. See test // case FlowNullness.java. + // As for the receiver, the refinement is skipped if evaluating a later argument might reassign + // the argument expression, as in `r.m(r, r = null)`. AnnotatedExecutableType methodType = nullnessTypeFactory.getAnnotatedType(method); List methodParams = methodType.getParameterTypes(); List methodArgs = tree.getArguments(); for (int i = 0; i < methodParams.size() && i < methodArgs.size(); ++i) { - if (methodParams.get(i).hasPrimaryAnnotation(NONNULL) - && (nonNullAssumptionAfterInvocation - || isMethodSideEffectFree - || !JavaExpression.fromTree(methodArgs.get(i)).isAssignableByOtherCode())) { - makeNonNull(result, n.getArgument(i)); + if (methodParams.get(i).hasPrimaryAnnotation(NONNULL)) { + JavaExpression argExpr = JavaExpression.fromTree(methodArgs.get(i)); + if ((nonNullAssumptionAfterInvocation + || isMethodSideEffectFree + || !argExpr.isAssignableByOtherCode()) + && !argumentsMayReassign(methodArgs.subList(i + 1, methodArgs.size()), argExpr)) { + makeNonNull(result, n.getArgument(i)); + } } } @@ -477,14 +512,66 @@ public TransferResult visitMethodInvocation( return result; } + /** + * Returns a transfer result like {@code result}, in which the receiver of {@code n} is non-null + * on each exceptional successor whose exception type excludes {@code NullPointerException}, such + * as a handler for a checked exception that the invoked method declares. An exception of such a + * type comes from the invoked method, which the invocation entered only because the receiver is + * non-null. + * + *

The receiver remains unrefined on the other exceptional successors. That loses no precision + * for an invocation in source code, because its {@code NullPointerException} for a null receiver + * comes from its {@code MethodAccessNode}, and every handler that such an edge of {@code n} + * reaches also catches that {@code NullPointerException}. But it is necessary for a synthetic + * invocation, such as the {@code iterator()} call of an enhanced {@code for} loop, which can + * throw that {@code NullPointerException} itself. + * + * @param n a method invocation whose receiver should be refined + * @param result the transfer result for {@code n} + * @param storeBefore the store before {@code n}; is not side-effected + * @return a transfer result like {@code result}, with the receiver refined on some exceptional + * successors + */ + private TransferResult refineReceiverOnExceptionalSuccessors( + MethodInvocationNode n, + TransferResult result, + NullnessStore storeBefore) { + if (!(n.getBlock() instanceof ExceptionBlock exceptionBlock)) { + return result; + } + Node receiver = n.getTarget().getReceiver(); + Map oldExceptionalStores = result.getExceptionalStores(); + Map newExceptionalStores = + oldExceptionalStores == null ? new HashMap<>() : new HashMap<>(oldExceptionalStores); + boolean refined = false; + for (TypeMirror exceptionType : exceptionBlock.getExceptionalSuccessors().keySet()) { + if (analysis.getTypes().isSubtype(nullPointerExceptionType, exceptionType)) { + continue; + } + NullnessStore exceptionalStore = newExceptionalStores.get(exceptionType); + NullnessStore refinedStore = + (exceptionalStore == null ? storeBefore : exceptionalStore).copy(); + makeNonNull(refinedStore, receiver); + newExceptionalStores.put(exceptionType, refinedStore); + refined = true; + } + return refined ? result.withExceptionalStores(newExceptionalStores) : result; + } + /** * Returns true if evaluating the given method arguments might reassign the given receiver - * expression or a subexpression of it. This is conservative. It returns true if an argument - * assigns any part of the receiver expression. If the receiver expression is assignable by other - * code, it also returns true if an argument assigns a non-local variable or (unless {@link + * expression or a subexpression of it. The "receiver" may also be an earlier argument of the + * invocation. This is conservative. It returns true if an argument assigns any part of the + * receiver expression. If the receiver expression is assignable by other code or contains a + * method call (whose value might depend on state that does not appear in the expression), it also + * returns true if an argument assigns a non-local variable or (unless {@link * #nonNullAssumptionAfterInvocation} is set) invokes a method or constructor that is not * side-effect-free. * + *

Matching a record pattern, as in {@code o instanceof R(int i)}, implicitly invokes the + * record's component accessors. This method handles them as it handles explicit method + * invocations. + * *

This method does not examine the bodies of lambda expressions and anonymous classes in the * arguments. Evaluating the arguments executes such a body only through a method or constructor * invocation (an anonymous class's initializers run as part of its constructor), which this @@ -499,7 +586,12 @@ private boolean argumentsMayReassign( if (arguments.isEmpty()) { return false; } - boolean receiverAssignableByOtherCode = receiverExpr.isAssignableByOtherCode(); + // A method call's value can depend on state that does not appear in the expression, such as a + // static field that the method reads. (MethodCall.isAssignableByOtherCode() examines only the + // receiver and arguments.) So, an assignment to a non-local variable or a call with side + // effects might change the value of a receiver that contains a method call. + boolean receiverMayChangeByOtherCode = + receiverExpr.isAssignableByOtherCode() || receiverExpr.containsOfClass(MethodCall.class); TreeScanner scanner = new TreeScanner() { @Override @@ -542,6 +634,19 @@ public Boolean visitNewClass(NewClassTree tree, Void p) { || super.visitNewClass(tree, p); } + // Matching a record pattern implicitly invokes the record's component accessors. + // TreeScanner has no visitDeconstructionPattern method before Java 21, so this method + // overrides scan instead. + @Override + public Boolean scan(@Nullable Tree tree, Void p) { + if (tree != null + && tree.getKind().name().equals("DECONSTRUCTION_PATTERN") + && recordPatternMayHaveSideEffect(tree)) { + return true; + } + return super.scan(tree, p); + } + // visitMethodInvocation and visitNewClass handle the invocations that execute the body // of a lambda expression or anonymous class. @@ -555,6 +660,13 @@ public Boolean visitClass(ClassTree tree, Void p) { return false; } + // An annotation is not evaluated at run time. Its element-value pairs, such as + // `value = 1`, are AssignmentTrees whose left-hand side is not a variable. + @Override + public Boolean visitAnnotation(AnnotationTree tree, Void p) { + return false; + } + /* * Returns true if assigning the given variable might reassign the receiver. * @@ -566,7 +678,28 @@ private boolean assignsReceiver(ExpressionTree variable) { if (receiverExpr.containsSyntacticEqualJavaExpression(assigned)) { return true; } - return receiverAssignableByOtherCode && !(assigned instanceof LocalVariable); + return receiverMayChangeByOtherCode && !(assigned instanceof LocalVariable); + } + + /* + * Returns true if matching the given record pattern might reassign the receiver, by + * invoking one of the record's component accessors. Does not examine nested patterns; + * scan visits them. + * + * @param recordPattern a record pattern (a deconstruction pattern) + * @return true if matching {@code recordPattern} might reassign the receiver + */ + private boolean recordPatternMayHaveSideEffect(Tree recordPattern) { + TypeElement recordElement = TypesUtils.getTypeElement(TreeUtils.typeOf(recordPattern)); + if (recordElement == null) { + return receiverMayChangeByOtherCode && !nonNullAssumptionAfterInvocation; + } + for (RecordComponentElement component : recordElement.getRecordComponents()) { + if (mayHaveSideEffect(component.getAccessor())) { + return true; + } + } + return false; } /* @@ -576,7 +709,7 @@ private boolean assignsReceiver(ExpressionTree variable) { * @return true if invoking {@code executable} might reassign the receiver */ private boolean mayHaveSideEffect(ExecutableElement executable) { - return receiverAssignableByOtherCode + return receiverMayChangeByOtherCode && !nonNullAssumptionAfterInvocation && !atypeFactory.isSideEffectFree(executable); } diff --git a/checker/tests/nullness/ReceiverDependsOnStaticField.java b/checker/tests/nullness/ReceiverDependsOnStaticField.java new file mode 100644 index 000000000000..b2a3a5b7cf37 --- /dev/null +++ b/checker/tests/nullness/ReceiverDependsOnStaticField.java @@ -0,0 +1,28 @@ +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.Pure; +import org.checkerframework.dataflow.qual.SideEffectFree; + +// The receiver of a call is a method call whose result depends on a static field. If an argument +// writes that static field, normal completion of the call does not show that the receiver +// expression is non-null afterward. See also ReceiverReassignedInArgument.java. +public class ReceiverDependsOnStaticField { + + static @Nullable ReceiverDependsOnStaticField slot; + + @Pure + static @Nullable ReceiverDependsOnStaticField current() { + return slot; + } + + @SideEffectFree + void sefAccept(@Nullable Object o) {} + + void directAssignment() { + if (current() == null) { + return; + } + current().sefAccept(slot = null); + // :: error: (dereference.of.nullable) + current().toString(); + } +} diff --git a/checker/tests/nullness/ReceiverReassignedInArgument.java b/checker/tests/nullness/ReceiverReassignedInArgument.java index 7dccf51638f3..4ed8c1bf8ee2 100644 --- a/checker/tests/nullness/ReceiverReassignedInArgument.java +++ b/checker/tests/nullness/ReceiverReassignedInArgument.java @@ -1,9 +1,13 @@ +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.qual.SideEffectFree; +import org.checkerframework.framework.qual.DoesNotUnrefineReceiver; // A call's receiver is evaluated before its arguments. If an argument reassigns the receiver // expression, then normal completion of the call does not show that the receiver expression is -// non-null afterward. ReceiverRefinementInCatch.java contains more such tests. +// non-null afterward. Likewise for an argument that a later argument reassigns. +// ReceiverRefinementInCatch.java contains more such tests. public class ReceiverReassignedInArgument { @Nullable ReceiverReassignedInArgument f; @@ -20,6 +24,14 @@ void assignInNestedArgument() { r.toString(); } + // The receiver is not refined while the arguments are evaluated. + void dereferenceInArgument(@Nullable ReceiverReassignedInArgument r) { + // :: error: (dereference.of.nullable) + r.equals( + // :: error: (dereference.of.nullable) + r.hashCode()); + } + // The argument assigns a non-null value to the receiver expression. void assignNonNullInArgument(@Nullable Object r, Object nn) { // :: error: (dereference.of.nullable) @@ -47,4 +59,64 @@ void assignInAnonymousClassInitializer() { // :: error: (dereference.of.nullable) f.toString(); } + + @SideEffectFree + void sefTake2(Object first, @Nullable Object second) {} + + // A later argument reassigns an earlier argument that is passed to a non-null parameter. + void assignEarlierArgument() { + ReceiverReassignedInArgument r = new ReceiverReassignedInArgument(); + r.sefTake2(r, r = null); + // :: error: (dereference.of.nullable) + r.toString(); + } + + // Without reassignment, an argument passed to a non-null parameter is non-null afterward. + void noReassignment(@Nullable Object q) { + // :: error: (argument) + sefTake2(q, null); + q.toString(); + } + + @Target(ElementType.TYPE_USE) + @interface TypeUseAnno { + int value(); + } + + // An annotation's element-value pair, such as `value = 1`, is not an assignment. + void annotationInArgument(Object r, @Nullable Object other) { + r.equals((@TypeUseAnno(value = 1) Object) other); + r.toString(); + } + + void sideEffect() {} + + @DoesNotUnrefineReceiver("allcheckers") + void doesNotUnrefineReceiver() {} + + @DoesNotUnrefineReceiver("allcheckers") + void doesNotUnrefineReceiver(@Nullable Object o) {} + + // The method does not unrefine its receiver, so normal completion shows that f is non-null. + void doesNotUnrefineReceiverField() { + // :: error: (dereference.of.nullable) + f.doesNotUnrefineReceiver(); + f.toString(); + } + + void sideEffectField() { + // :: error: (dereference.of.nullable) + f.sideEffect(); + // :: error: (dereference.of.nullable) + f.toString(); + } + + // An argument that reassigns the receiver blocks the refinement, even if the method does not + // unrefine its receiver. + void doesNotUnrefineReceiverArgumentReassigns() { + // :: error: (dereference.of.nullable) + f.doesNotUnrefineReceiver(f = null); + // :: error: (dereference.of.nullable) + f.toString(); + } } diff --git a/checker/tests/nullness/ReceiverRefinementInCatch.java b/checker/tests/nullness/ReceiverRefinementInCatch.java index d966dac7b8af..aa63d2898607 100644 --- a/checker/tests/nullness/ReceiverRefinementInCatch.java +++ b/checker/tests/nullness/ReceiverRefinementInCatch.java @@ -14,6 +14,41 @@ void m(@Nullable Object o) { } } + void read() throws java.io.IOException {} + + // A null receiver causes a NullPointerException, which a handler for IOException does not catch. + // So the receiver is non-null in that handler. + void checkedExceptionHandler(@Nullable ReceiverRefinementInCatch r) { + try { + // :: error: (dereference.of.nullable) + r.read(); + } catch (java.io.IOException e) { + r.toString(); + } + } + + void checkedAndRuntimeExceptionHandlers(@Nullable ReceiverRefinementInCatch r) { + try { + // :: error: (dereference.of.nullable) + r.read(); + } catch (java.io.IOException e) { + r.toString(); + } catch (RuntimeException e) { + // :: error: (dereference.of.nullable) + r.toString(); + } + } + + // An Error handler cannot catch the NullPointerException either. + void errorHandler(@Nullable Object o) { + try { + // :: error: (dereference.of.nullable) + o.toString(); + } catch (Error e) { + o.hashCode(); + } + } + void afterNormalCompletion(@Nullable Object o) { // :: error: (dereference.of.nullable) o.toString(); diff --git a/checker/tests/nullness/java21/ReceiverReassignedInRecordPattern.java b/checker/tests/nullness/java21/ReceiverReassignedInRecordPattern.java new file mode 100644 index 000000000000..a1754fd32532 --- /dev/null +++ b/checker/tests/nullness/java21/ReceiverReassignedInRecordPattern.java @@ -0,0 +1,49 @@ +// @below-java21-jdk-skip-test + +// None of the WPI formats supports the new Java 21 language features, so skip inference until they +// do. +// @infer-jaifs-skip-test +// @infer-ajava-skip-test +// @infer-stubs-skip-test + +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.Pure; +import org.checkerframework.dataflow.qual.SideEffectFree; + +// Matching a record pattern in an argument implicitly invokes the record's component accessors, +// which might reassign the receiver of the call. +public class ReceiverReassignedInRecordPattern { + + static @Nullable ReceiverReassignedInRecordPattern f; + + @SideEffectFree + void sefAccept(boolean b) {} + + record Clearing(int n) { + // An accessor that has a side effect. + public int n() { + f = null; + return n; + } + } + + record Plain(int n) { + @Pure + public int n() { + return n; + } + } + + void accessorReassignsReceiver(Object rec) { + // :: error: (dereference.of.nullable) + f.sefAccept(rec instanceof Clearing(int n)); + // :: error: (dereference.of.nullable) + f.toString(); + } + + void pureAccessor(Object rec) { + // :: error: (dereference.of.nullable) + f.sefAccept(rec instanceof Plain(int n)); + f.toString(); + } +} diff --git a/framework/tests/flow/ReceiverNullPointerException.java b/framework/tests/flow/ReceiverNullPointerException.java index 1abe2bc9493f..13048abb2cb9 100644 --- a/framework/tests/flow/ReceiverNullPointerException.java +++ b/framework/tests/flow/ReceiverNullPointerException.java @@ -292,6 +292,18 @@ void methodCallMayBeNull(@Odd String p1, String p2, String s) { } } + // The call has an exceptional edge after its argument is evaluated. No other node in the try + // block can throw a NullPointerException after `l1 = p2`. + void methodCallMayBeNullAfterArgument(@Odd String p1, String p2, String s) { + String l1 = p1; + try { + s.equals(l1 = p2); + } catch (NullPointerException e) { + // :: error: [assignment] + @Odd String l3 = l1; + } + } + class Inner { void qualifiedThis(@Odd String p1, String p2) { String l1 = p1; From f29d1d830b1b57b9699dbecf154a52e9a55e1df0 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 20:53:34 -0800 Subject: [PATCH 58/98] Clarify where the primary-exception edges of a suppressed close() call lead --- .../cfg/builder/CFGTranslationPhaseOne.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index be6b308cb5f7..6fc11f0c649b 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2845,13 +2845,13 @@ private void addCloseCallForResource( * IllegalArgumentException}, which {@code addSuppressed} throws if {@code close} threw the * primary exception itself; otherwise it reaches the rethrow of the primary exception. * - *

The types of the primary exception label exceptional edges of the call to the rethrow, in - * addition to the types of the exceptions that {@code close} might throw. So an analysis that - * ignores some exception types follows those edges, with the exceptional store of the call, - * whenever it follows the rethrow of the primary exception -- even if it ignores every exception - * that {@code close} might throw. Otherwise, if {@code close} terminates execution and might - * throw only ignored exceptions, the analysis would consider the rethrow of the primary exception - * unreachable. + *

The types of the primary exception label exceptional edges of the call, which lead to the + * rethrow, in addition to the types of the exceptions that {@code close} might throw. So an + * analysis that ignores some exception types follows those edges, with the exceptional store of + * the call, whenever it follows the rethrow of the primary exception -- even if it ignores every + * exception that {@code close} might throw. Otherwise, if {@code close} terminates execution and + * might throw only ignored exceptions, the analysis would consider the rethrow of the primary + * exception unreachable. * *

The call follows those edges whenever {@code close} throws an exception, whatever its type, * so the call records their types (see {@link MethodInvocationNode#getAnyExceptionTypes()}). An From 67fbe5eed9ca510538c7654a59f3e25676319cd1 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 20:53:47 -0800 Subject: [PATCH 59/98] Test self-suppression and the primary exception of try-with-resources Add TryWithResourcesSelfSuppression.java, which fails without the addSuppressed() IllegalArgumentException edge, and TryWithResourcesPrimaryException.primaryExceptionNotReplaced. Suppress declaration.inconsistent.with.implements.clause on FinishingTerminatingClose, whose @InheritableMustCall is stronger than that of Closeable. --- .../TryWithResourcesSelfSuppression.java | 28 ++++++++++++++++ .../TryWithResourcesPrimaryException.java | 33 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 checker/tests/nullness/TryWithResourcesSelfSuppression.java diff --git a/checker/tests/nullness/TryWithResourcesSelfSuppression.java b/checker/tests/nullness/TryWithResourcesSelfSuppression.java new file mode 100644 index 000000000000..87809b38ac6b --- /dev/null +++ b/checker/tests/nullness/TryWithResourcesSelfSuppression.java @@ -0,0 +1,28 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// A try-with-resources statement suppresses an exception that close() throws by calling +// addSuppressed() on the primary exception. If close() throws the primary exception itself, then +// addSuppressed() throws an IllegalArgumentException, which replaces the primary exception. +public class TryWithResourcesSelfSuppression { + + static class MyException extends Exception {} + + interface Resource extends AutoCloseable { + @Override + void close(); + } + + void selfSuppression(Resource r, MyException ex) throws MyException { + @Nullable Object o = ""; + try { + try (r) { + o = null; + throw ex; + } + } catch (IllegalArgumentException e) { + // The handler is reachable only through the addSuppressed() call. + // :: error: (dereference.of.nullable) + o.toString(); + } + } +} diff --git a/checker/tests/resourceleak/TryWithResourcesPrimaryException.java b/checker/tests/resourceleak/TryWithResourcesPrimaryException.java index 05a169ce55ae..631fa704358c 100644 --- a/checker/tests/resourceleak/TryWithResourcesPrimaryException.java +++ b/checker/tests/resourceleak/TryWithResourcesPrimaryException.java @@ -58,6 +58,8 @@ void leakWhenTryBlockThrowsAndCloseTerminates() throws IOException { // A resource whose close() promises to call finish() if close() throws an Exception, but which // terminates execution by throwing an Error without calling finish(). @InheritableMustCall({"close", "finish"}) + @SuppressWarnings( + "declaration.inconsistent.with.implements.clause") // stronger @InheritableMustCall abstract static class FinishingTerminatingClose implements Closeable { abstract void finish(); @@ -78,4 +80,35 @@ void finishNotCalledWhenTryBlockThrowsAndCloseTerminates() throws IOException { r.finish(); } } + + static class CloseException extends Exception {} + + interface ResourceWithCloseException extends AutoCloseable { + @Override + void close() throws CloseException; + } + + public abstract @Owning ResourceWithCloseException allocWithCloseException(); + + public abstract void alwaysThrows() throws IOException; + + // The try block always throws an IOException. If close() throws a CloseException, the statement + // suppresses it and rethrows the IOException, so the CloseException handler is unreachable. The + // IOException handler closes c. If the CloseException replaced the IOException, then c would + // leak on the path through the CloseException handler. The IllegalArgumentException handler + // closes c too: the statement suppresses the CloseException by calling addSuppressed(), which + // throws an IllegalArgumentException if close() threw the primary exception itself. + void primaryExceptionNotReplaced() throws IOException { + Closeable c = allocWithoutException(); + try { + try (ResourceWithCloseException r = allocWithCloseException()) { + alwaysThrows(); + throw new Error(); + } + } catch (IOException | IllegalArgumentException e) { + c.close(); + } catch (CloseException e) { + // unreachable + } + } } From be99508686ffbfcd857a9b497c851c3f47ef2c2c Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 21:08:35 -0800 Subject: [PATCH 60/98] Pass an unmodifiable view of the rethrown exception types to the finally-block generator --- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index d903512fecc2..7ac587da2e25 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -3013,7 +3013,7 @@ private void handleFinally( + TreeUtils.treeUids.get(markerTree), env.getTypeUtils())); - exceptionalFinallyBlockCFGGenerator.accept(group.keySet()); + exceptionalFinallyBlockCFGGenerator.accept(Collections.unmodifiableSet(group.keySet())); NodeWithExceptionsHolder throwing = extendWithNodeWithExceptions( From 056f4076670a0b1b85e3625c461e213cc0d40f45 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 22 Nov 2026 21:19:40 -0800 Subject: [PATCH 61/98] Introduce RethrowGroup; clarify documentation of exceptional copies of finally blocks --- .../dataflow/cfg/ControlFlowGraph.java | 2 + .../cfg/builder/CFGTranslationPhaseOne.java | 85 ++++++++++--------- .../dataflow/cfg/builder/RethrowGroup.java | 79 +++++++++++++++++ .../dataflow/cfg/builder/TryFinallyFrame.java | 40 ++++++--- 4 files changed, 157 insertions(+), 49 deletions(-) create mode 100644 dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java index a19d6097bc41..f22652b9bce9 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java @@ -151,10 +151,12 @@ public ControlFlowGraph( */ public void checkInvariants() { // TODO: this is a big data structure with many more invariants... + // The predecessors of each block, computed once per block. Block.getPredecessors takes time // quadratic in the number of predecessors, and a block such as the exceptional exit can have // thousands of predecessors. IdentityHashMap> predecessors = new IdentityHashMap<>(); + for (Block b : getAllBlocks()) { // Each node in the block should have this block as its parent. diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index cbe07c53cda7..8f5fd27bd964 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -288,14 +288,18 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** * The maximum number of nodes in extra exceptional copies of finally blocks, beyond which the - * exceptions that reach a finally block share one copy. An extra copy is one other than the first - * exceptional copy of a given finally block. See {@link #handleFinally}. + * remaining exception types that reach a finally block share one exceptional copy of that finally + * block. An exceptional copy of a finally block is a translation of the finally block that runs + * when an exception reaches the finally block, and that rethrows the exception after the finally + * block completes normally. An extra copy is one other than the first exceptional copy of a given + * finally block. See {@link #handleFinally}. */ private static final int EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET = 10_000; /** - * The number of nodes in extra exceptional copies of finally blocks so far. Nodes in nested extra - * copies are counted more than once. + * The number of nodes in extra exceptional copies of finally blocks so far. A node is counted + * once for each extra copy that contains it, so a node in an extra copy that is nested within + * another extra copy is counted more than once. */ private int extraExceptionalFinallyNodes = 0; @@ -2876,42 +2880,44 @@ private void handleFinally( extendWithExtendedNode(new UnconditionalJump(doneLabel)); } - // For each type of exception that reaches the finally block, a copy of the finally block - // rethrows that type after the finally block completes normally. Two types share a copy if - // and only if the copy rethrows them to the same places: the same catch blocks, or the exit, - // past any enclosing finally blocks. The analysis merges the stores of the paths that reach a - // copy. Types that go to different places get different copies, so that the analysis does - // not merge stores of paths that never meet. For example, the Resource Leak Checker would - // otherwise report a leak when an exception thrown while a resource is open is caught by a - // catch block that closes the resource, and another exception, thrown after the resource is - // closed, propagates out of the method. Types that go to the same places share a copy, because - // the analysis merges their stores there anyway. The number of copies grows exponentially with - // the depth of the nesting of finally blocks in finally blocks, with a base that grows with the - // number of copies per finally block. A copy for each type would make the base much larger. - // To bound that growth, once the copies beyond the first copy for each finally block have - // contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the remaining groups of each - // finally block share a single copy, which rethrows each of their exceptions. - List> groups = new ArrayList<>(exceptionGroups(exceptionalFinallyFrame)); + // `groups` partitions the types of the exceptions that reach the finally block. For each + // group, a copy of the finally block starts at the group's entry labels, which exceptions of + // the group's types jump to when they reach the finally block, and the copy rethrows the + // group's types after the finally block completes normally. Types that go to the same places + // share a copy, because the analysis merges their stores there anyway. The number of copies + // grows exponentially with the depth of the nesting of finally blocks in finally blocks, with + // a base that grows with the number of copies per finally block. + // + // As an optimization, two types share a copy if and only if the copy rethrows them to the same + // places: the same catch blocks, or the exit, past any enclosing finally blocks. The analysis + // merges the stores of the paths that reach a copy. Types that go to different places get + // different copies, so that the analysis does not merge stores of paths that never meet. For + // example, the Resource Leak Checker would otherwise report a leak when an exception thrown + // while a resource is open is caught by a catch block that closes the resource, and another + // exception, thrown after the resource is closed, propagates out of the method. + // + // As a further optimization, to bound growth, once the copies beyond the first copy for each + // finally block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the remaining + // groups of each finally block share a single copy, which rethrows each of their exceptions. + List groups = new ArrayList<>(rethrowGroups(exceptionalFinallyFrame)); + for (int i = 0; i < groups.size(); i++) { - Map group = groups.get(i); + RethrowGroup group = groups.get(i); boolean isExtraCopy = i > 0; if (isExtraCopy && extraExceptionalFinallyNodes >= EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET && i < groups.size() - 1) { - Map sharedGroup = new ArrayMap<>(); - for (Map remainingGroup : groups.subList(i, groups.size())) { - sharedGroup.putAll(remainingGroup); - } - groups.subList(i, groups.size()).clear(); - groups.add(sharedGroup); - group = sharedGroup; + List remainingGroups = groups.subList(i, groups.size()); + group = RethrowGroup.merge(remainingGroups); + remainingGroups.clear(); + groups.add(group); } int sizeBeforeCopy = nodeList.size(); - for (Label label : group.values()) { + for (Label label : group.entryLabels()) { addLabelForNextNode(label); } - String exceptionsString = group.keySet().toString(); + String exceptionsString = group.types().toString(); extendWithNode( new MarkerNode( markerTree, @@ -2932,12 +2938,13 @@ private void handleFinally( + " #" + TreeUtils.treeUids.get(markerTree), env.getTypeUtils()), - Collections.unmodifiableSet(group.keySet())); + group.types()); throwing.setTerminatesExecution(true); if (isExtraCopy) { - // This overcounts the nodes of a nested extra copy, which is conservative. + // The inner `handleFinally` already counted the nodes of any extra copy nested in this + // one, so this counts them again, which is conservative. extraExceptionalFinallyNodes += nodeList.size() - sizeBeforeCopy; } } @@ -3068,17 +3075,17 @@ private void handleFinally( * TryStack#possibleLabelsPastFinally} returns the same set of labels for each of them. * * @param frame a frame for a finally block, which the CFG builder has popped from the try stack - * @return the groups, in the order that the first type of each group reaches {@code frame} (see - * {@link TryFinallyFrame#getExceptionLabels}); each group maps each of its types to the - * type's label in {@code frame}. Empty if no exception reaches {@code frame}. + * @return the groups, in a deterministic order: the order in which the first type of each group + * reaches {@code frame} (see {@link TryFinallyFrame#getExceptionLabels}); the entry label of + * each type is its label in {@code frame}. Empty if no exception reaches {@code frame}. */ - private Collection> exceptionGroups(TryFinallyFrame frame) { - Map, Map> groups = new LinkedHashMap<>(); + private Collection rethrowGroups(TryFinallyFrame frame) { + Map, RethrowGroup> groups = new LinkedHashMap<>(); for (Map.Entry entry : frame.getExceptionLabels().entrySet()) { TypeMirror type = entry.getKey(); groups - .computeIfAbsent(tryStack.possibleLabelsPastFinally(type), labels -> new ArrayMap<>()) - .put(type, entry.getValue()); + .computeIfAbsent(tryStack.possibleLabelsPastFinally(type), labels -> new RethrowGroup()) + .add(type, entry.getValue()); } return groups.values(); } diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java new file mode 100644 index 000000000000..918935efa1de --- /dev/null +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java @@ -0,0 +1,79 @@ +package org.checkerframework.dataflow.cfg.builder; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.lang.model.type.TypeMirror; +import org.plumelib.util.ArrayMap; + +/** + * Some of the types of the exceptions that reach a finally block (as defined in the documentation + * of {@link TryFinallyFrame}), such as {@code java.io.IOException} and {@code + * java.lang.RuntimeException}, all of which one copy of the finally block rethrows after the + * finally block completes normally. Each type has an entry label: the label that an exception of + * the type jumps to when it reaches the finally block (see {@link + * TryFinallyFrame#getExceptionLabels}). The copy starts at the entry labels of all the types in its + * group. + */ +/*package-private*/ final class RethrowGroup { + + /** + * The entry label of each type in this group, in a deterministic order: the order in which the + * types first reach the finally block. Like the map in {@link TryFinallyFrame}, it contains few + * entries. + */ + private final Map entryLabels = new ArrayMap<>(); + + /** Creates an empty RethrowGroup. */ + /*package-private*/ RethrowGroup() {} + + /** + * Adds the given type to this group. + * + * @param type a type of exception that reaches the finally block and is not in this group + * @param entryLabel the label that an exception of type {@code type} jumps to when it reaches the + * finally block + */ + /*package-private*/ void add(TypeMirror type, Label entryLabel) { + entryLabels.put(type, entryLabel); + } + + /** + * Returns the types in this group. + * + * @return the types in this group, in a deterministic order + */ + /*package-private*/ Set types() { + return Collections.unmodifiableSet(entryLabels.keySet()); + } + + /** + * Returns the entry labels of the types in this group. + * + * @return the entry labels of the types in this group, in the same order as {@link #types} + */ + /*package-private*/ Collection

A type reaches a TryFinallyFrame if, while the frame is on the try stack, the CFG builder + * creates a node that it records as possibly throwing that exact type, and no frame nearer the top + * of the try stack is certain to catch the type. For example, the CFG builder records a method + * invocation as possibly throwing each type in the method's {@code throws} clause, plus {@code + * java.lang.RuntimeException} and {@code java.lang.Error}. A subtype of a type that reaches the + * frame does not reach the frame unless some node is recorded as throwing the subtype itself. For + * example, if the only node in a try block is an invocation of a static method that has no {@code + * throws} clause, then {@code java.lang.RuntimeException} and {@code java.lang.Error} reach the + * frame, but {@code java.lang.NullPointerException} does not. */ /*package-private*/ class TryFinallyFrame implements TryFrame { /** The type utilities, used to give each type a single label. */ protected final Types types; /** - * A label for each type of exception that reaches this frame, in the order that the CFG builder - * first creates a node that throws the type to this frame. No two keys are the same type - * according to {@link Types#isSameType}, even if {@link TypeMirror#equals} would distinguish - * them. + * A label for each type of exception that reaches this frame (as defined in the documentation of + * {@link TryFinallyFrame}). No two keys are the same type according to {@link Types#isSameType}, + * even if {@link TypeMirror#equals} would distinguish them. + * + *

The keys are in a deterministic order: the order in which the CFG builder first creates a + * node that throws the type to this frame. Any deterministic order would do; it makes the CFG, + * such as the order of the copies of the finally block, the same on every run. + * + *

The map contains few entries, usually only a handful, so it is an {@link ArrayMap}. The + * types that reach a frame are {@code java.lang.RuntimeException} and {@code java.lang.Error}, + * which every invocation is recorded as possibly throwing; a few other unchecked types such as + * {@code java.lang.NullPointerException} and {@code java.lang.ArithmeticException}; and the + * checked exceptions in the {@code throws} clauses of the invoked methods and constructors. */ private final Map exceptionLabels = new ArrayMap<>(); @@ -62,11 +81,12 @@ private Label labelFor(TypeMirror thrown) { } /** - * Returns a label for each type of exception that reaches this frame. + * Returns a label for each type of exception that reaches this frame (as defined in the + * documentation of {@link TryFinallyFrame}). * * @return a map from each type of exception that reaches this frame, such as {@code - * java.io.IOException}, to its label, in the order that the types first reach this frame (see - * {@link #exceptionLabels}); empty if no exception reaches this frame + * java.io.IOException}, to its label, in a deterministic order (see {@link + * #exceptionLabels}); empty if no exception reaches this frame */ public Map getExceptionLabels() { return Collections.unmodifiableMap(exceptionLabels); From 49c60dbb49d75a9bea111b642fb1e29b669c53ec Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 22 Nov 2026 21:21:51 -0800 Subject: [PATCH 62/98] Account for implicit toString() calls in string conversion; qualify finally rethrow in manual --- .../checker/nullness/NullnessTransfer.java | 61 ++++++++++++++++++- .../ReceiverReassignedInArgument.java | 40 ++++++++++++ dataflow/manual/content.tex | 9 ++- 3 files changed, 106 insertions(+), 4 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index cbed0489a6fb..2feb5c8aa7f6 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -2,6 +2,7 @@ import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; +import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; @@ -52,6 +53,7 @@ import org.checkerframework.javacutil.AnnotationBuilder; import org.checkerframework.javacutil.AnnotationMirrorSet; import org.checkerframework.javacutil.AnnotationUtils; +import org.checkerframework.javacutil.ElementUtils; import org.checkerframework.javacutil.TreeUtils; import org.checkerframework.javacutil.TypeSystemError; import org.checkerframework.javacutil.TypesUtils; @@ -111,6 +113,9 @@ public class NullnessTransfer /** The type {@code java.lang.NullPointerException}. */ private final TypeMirror nullPointerExceptionType; + /** The method {@code Object.toString()}. */ + private final ExecutableElement objectToString; + /** * Create a new NullnessTransfer for the given analysis. * @@ -150,6 +155,8 @@ public NullnessTransfer(NullnessAnalysis analysis) { nullPointerExceptionType = TypesUtils.typeFromClass(NullPointerException.class, analysis.getTypes(), elements); + + objectToString = TreeUtils.getMethod("java.lang.Object", "toString", 0, analysis.getEnv()); } /** @@ -606,7 +613,22 @@ public Boolean visitAssignment(AssignmentTree tree, Void p) { @Override public Boolean visitCompoundAssignment(CompoundAssignmentTree tree, Void p) { - return assignsReceiver(tree.getVariable()) || super.visitCompoundAssignment(tree, p); + // `s += o`, for a String variable s, implicitly invokes o.toString(). + return assignsReceiver(tree.getVariable()) + || (tree.getKind() == Tree.Kind.PLUS_ASSIGNMENT + && TypesUtils.isString(TreeUtils.typeOf(tree.getVariable())) + && stringConversionMayHaveSideEffect(tree.getExpression())) + || super.visitCompoundAssignment(tree, p); + } + + // String concatenation implicitly invokes toString() on an operand that is not a String. + @Override + public Boolean visitBinary(BinaryTree tree, Void p) { + return (tree.getKind() == Tree.Kind.PLUS + && TypesUtils.isString(TreeUtils.typeOf(tree)) + && (stringConversionMayHaveSideEffect(tree.getLeftOperand()) + || stringConversionMayHaveSideEffect(tree.getRightOperand()))) + || super.visitBinary(tree, p); } @Override @@ -702,6 +724,43 @@ private boolean recordPatternMayHaveSideEffect(Tree recordPattern) { return false; } + /* + * Returns true if converting the given expression to a string, as string concatenation + * does, might reassign the receiver by invoking a toString() method. Does not examine + * the subexpressions of the operand; scan visits them. + * + * @param operand an operand of string concatenation + * @return true if converting {@code operand} to a string might reassign the receiver + */ + private boolean stringConversionMayHaveSideEffect(ExpressionTree operand) { + TypeMirror type = TreeUtils.typeOf(operand); + if (type.getKind().isPrimitive() + || type.getKind() == TypeKind.NULL + || TypesUtils.isString(type)) { + return false; + } + TypeElement typeElement = + TypesUtils.getTypeElement(analysis.getTypes().erasure(type)); + if (typeElement == null) { + // For example, an array type. + return mayHaveSideEffect(objectToString); + } + // As for an explicit invocation, use the toString() methods of the static type. + // getAllMethodsIn also returns overridden methods, which is conservative. + boolean foundToString = false; + for (ExecutableElement m : + ElementUtils.getAllMethodsIn(typeElement, nullnessTypeFactory.getElementUtils())) { + if (m.getSimpleName().contentEquals("toString") && m.getParameters().isEmpty()) { + foundToString = true; + if (mayHaveSideEffect(m)) { + return true; + } + } + } + // An interface need not declare or inherit a toString() method. + return !foundToString && mayHaveSideEffect(objectToString); + } + /* * Returns true if invoking the given method or constructor might reassign the receiver. * diff --git a/checker/tests/nullness/ReceiverReassignedInArgument.java b/checker/tests/nullness/ReceiverReassignedInArgument.java index 4ed8c1bf8ee2..ebb4a26177be 100644 --- a/checker/tests/nullness/ReceiverReassignedInArgument.java +++ b/checker/tests/nullness/ReceiverReassignedInArgument.java @@ -78,6 +78,46 @@ void noReassignment(@Nullable Object q) { q.toString(); } + // A toString() method that reassigns the field f. + class Mutator { + @Override + public String toString() { + f = null; + return ""; + } + } + + class SefToString { + @Override + @SideEffectFree + public String toString() { + return ""; + } + } + + // String concatenation implicitly invokes Mutator.toString(), which reassigns f. + void stringConcatenationInArgument(Mutator m) { + // :: error: (dereference.of.nullable) + f.sefTake("" + m); + // :: error: (dereference.of.nullable) + f.toString(); + } + + // `s += m` implicitly invokes Mutator.toString(), which reassigns f. + void stringCompoundAssignmentInArgument(Mutator m, String s) { + // :: error: (dereference.of.nullable) + f.sefTake(s += m); + // :: error: (dereference.of.nullable) + f.toString(); + } + + // String concatenation of an operand whose toString() is side-effect-free. + void sefStringConcatenationInArgument(SefToString o, int i) { + // :: error: (dereference.of.nullable) + f.sefTake("" + o + i); + f.toString(); + } + @Target(ElementType.TYPE_USE) @interface TypeUseAnno { int value(); diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 92296ea5a19f..f3a28bb30614 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -1224,9 +1224,12 @@ \subsubsection{Handling \code{finally} blocks} Likewise, an exception that the \code{try} block or a \code{catch} block throws causes execution of the \code{finally} block, which then rethrows the -exception. The Dataflow Framework models this behavior with further -duplicates of the \code{finally} block, each of which ends by rethrowing the -exception. Exception types that would be rethrown to the same places (the +exception if the \code{finally} block completes normally. (If the +\code{finally} block completes abruptly, for example by a \code{return} or +\code{throw}, then that replaces the pending exception, which is not +rethrown.) The Dataflow Framework models this behavior with further +duplicates of the \code{finally} block, each of which ends, if the +\code{finally} block completes normally, by rethrowing the exception. Exception types that would be rethrown to the same places (the same \code{catch} blocks, or the exit of the method) share a duplicate. Exception types that would be rethrown to different places get different duplicates, so that the analysis does not merge the stores of paths that From 7a63e7df99889e94761c3056892da2b784c8c8a7 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 22 Nov 2026 21:29:38 -0800 Subject: [PATCH 63/98] Once the budget is used up, give each finally block one exceptional copy; remove unused throwableType --- .../cfg/builder/CFGTranslationPhaseOne.java | 37 +++++++++---------- .../dataflow/cfg/builder/RethrowGroup.java | 3 +- .../dataflow/cfg/builder/TryFinallyFrame.java | 7 +++- 3 files changed, 25 insertions(+), 22 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 8f5fd27bd964..6c6ef0f7a7c4 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -287,12 +287,14 @@ public class CFGTranslationPhaseOne extends TreeScanner { private SwitchBuilder switchBuilder; /** - * The maximum number of nodes in extra exceptional copies of finally blocks, beyond which the - * remaining exception types that reach a finally block share one exceptional copy of that finally - * block. An exceptional copy of a finally block is a translation of the finally block that runs - * when an exception reaches the finally block, and that rethrows the exception after the finally - * block completes normally. An extra copy is one other than the first exceptional copy of a given - * finally block. See {@link #handleFinally}. + * The maximum number of nodes in extra exceptional copies of finally blocks. Once the extra + * copies contain this many nodes, the exception types that reach a finally block and do not yet + * have a copy share one exceptional copy of that finally block, so a finally block that the CFG + * builder translates after that point has only one exceptional copy. An exceptional copy of a + * finally block is a translation of the finally block that runs when an exception reaches the + * finally block, and that rethrows the exception after the finally block completes normally. An + * extra copy is one other than the first exceptional copy of a given finally block. See {@link + * #handleFinally}. */ private static final int EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET = 10_000; @@ -386,9 +388,6 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** The String type. */ protected final TypeMirror stringType; - /** The Throwable type. */ - protected final TypeMirror throwableType; - /** * Supertypes of all unchecked exceptions. The size is 2 and the contents are {@code * RuntimeException} and {@code Error}. @@ -466,7 +465,6 @@ public CFGTranslationPhaseOne( classFormatErrorType = maybeGetTypeMirror(ClassFormatError.class); noClassDefFoundErrorType = maybeGetTypeMirror(NoClassDefFoundError.class); stringType = getTypeMirror(String.class); - throwableType = getTypeMirror(Throwable.class); uncheckedExceptionTypes = new ArraySet<>(2); uncheckedExceptionTypes.add(getTypeMirror(RuntimeException.class)); @@ -2897,21 +2895,22 @@ private void handleFinally( // exception, thrown after the resource is closed, propagates out of the method. // // As a further optimization, to bound growth, once the copies beyond the first copy for each - // finally block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the remaining - // groups of each finally block share a single copy, which rethrows each of their exceptions. + // finally block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that + // do not yet have a copy share a single copy, which rethrows each of their exceptions. A + // finally block that the CFG builder translates after that point has a single exceptional + // copy, which all of its groups share, as if all of its exceptions went to the same places. List groups = new ArrayList<>(rethrowGroups(exceptionalFinallyFrame)); for (int i = 0; i < groups.size(); i++) { - RethrowGroup group = groups.get(i); - boolean isExtraCopy = i > 0; - if (isExtraCopy - && extraExceptionalFinallyNodes >= EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET - && i < groups.size() - 1) { + if (i < groups.size() - 1 + && extraExceptionalFinallyNodes >= EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET) { List remainingGroups = groups.subList(i, groups.size()); - group = RethrowGroup.merge(remainingGroups); + RethrowGroup sharedGroup = RethrowGroup.merge(remainingGroups); remainingGroups.clear(); - groups.add(group); + groups.add(sharedGroup); } + RethrowGroup group = groups.get(i); + boolean isExtraCopy = i > 0; int sizeBeforeCopy = nodeList.size(); for (Label label : group.entryLabels()) { diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java index 918935efa1de..c933515fae84 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java @@ -61,7 +61,8 @@ /** * Returns a new group that contains every type in the given groups. * - * @param groups groups for the same finally block, no two of which contain the same type + * @param groups a list of groups for the same finally block, no two of which contain the same + * type * @return a new group that contains every type in {@code groups}, in the order of {@code groups} */ /*package-private*/ static RethrowGroup merge(List groups) { diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java index e187b0f49ed9..9f55ce42bd60 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java @@ -38,8 +38,11 @@ *

The map contains few entries, usually only a handful, so it is an {@link ArrayMap}. The * types that reach a frame are {@code java.lang.RuntimeException} and {@code java.lang.Error}, * which every invocation is recorded as possibly throwing; a few other unchecked types such as - * {@code java.lang.NullPointerException} and {@code java.lang.ArithmeticException}; and the - * checked exceptions in the {@code throws} clauses of the invoked methods and constructors. + * {@code java.lang.NullPointerException} and {@code java.lang.ArithmeticException}; the checked + * exceptions in the {@code throws} clauses of the invoked methods and constructors; and the + * static types of the expressions in {@code throw} statements, such as {@code + * java.io.IOException} for {@code throw new IOException()}. The copies of nested finally blocks + * rethrow types of these same kinds. */ private final Map exceptionLabels = new ArrayMap<>(); From d26ce8001db12c3364dda5c8a9c1a3aecb340642 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 23 Nov 2026 00:08:24 -0800 Subject: [PATCH 64/98] Fix the build after merging branch 'finally-rethrow-exception-types' --- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index a83cca62dfd1..4213978ecac8 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -392,6 +392,9 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** The String type. */ protected final TypeMirror stringType; + /** The Throwable type. */ + protected final TypeMirror throwableType; + /** * Supertypes of all unchecked exceptions. The size is 2 and the contents are {@code * RuntimeException} and {@code Error}. @@ -470,6 +473,7 @@ public CFGTranslationPhaseOne( classFormatErrorType = maybeGetTypeMirror(ClassFormatError.class); noClassDefFoundErrorType = maybeGetTypeMirror(NoClassDefFoundError.class); stringType = getTypeMirror(String.class); + throwableType = getTypeMirror(Throwable.class); uncheckedExceptionTypes = new ArraySet<>(2); uncheckedExceptionTypes.add(getTypeMirror(RuntimeException.class)); @@ -3018,7 +3022,7 @@ private void handleFinally( + TreeUtils.treeUids.get(markerTree), env.getTypeUtils())); - exceptionalFinallyBlockCFGGenerator.accept(Collections.unmodifiableSet(group.keySet())); + exceptionalFinallyBlockCFGGenerator.accept(group.types()); NodeWithExceptionsHolder throwing = extendWithNodeWithExceptions( From 9131f863889804da2fe2963d856b748ed6dfe987 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 23 Nov 2026 00:10:04 -0800 Subject: [PATCH 65/98] Reformat --- .../checkerframework/checker/nullness/NullnessTransfer.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 2feb5c8aa7f6..64719b322727 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -739,8 +739,7 @@ private boolean stringConversionMayHaveSideEffect(ExpressionTree operand) { || TypesUtils.isString(type)) { return false; } - TypeElement typeElement = - TypesUtils.getTypeElement(analysis.getTypes().erasure(type)); + TypeElement typeElement = TypesUtils.getTypeElement(analysis.getTypes().erasure(type)); if (typeElement == null) { // For example, an array type. return mayHaveSideEffect(objectToString); From a0de79ca8e502199ccf1a43d21811e2d62f03c4e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 23 Nov 2026 07:40:37 -0800 Subject: [PATCH 66/98] Test the success-flag false positive and a non-ignored throwable; document the bound on finally copies --- .../FinallyRethrowsException.java | 37 +++++++++++++++---- dataflow/manual/content.tex | 7 +++- .../cfg/builder/CFGTranslationPhaseOne.java | 15 ++++---- docs/CHANGELOG.md | 7 ++++ 4 files changed, 51 insertions(+), 15 deletions(-) diff --git a/checker/tests/resourceleak/FinallyRethrowsException.java b/checker/tests/resourceleak/FinallyRethrowsException.java index 3bdf1ea022ec..cbbdca70ed5c 100644 --- a/checker/tests/resourceleak/FinallyRethrowsException.java +++ b/checker/tests/resourceleak/FinallyRethrowsException.java @@ -1,5 +1,5 @@ // Tests that an exception that a finally block rethrows is not ignored. The exceptions are an -// IOException and a MyChecked, which the Resource Leak Checker does not ignore. +// IOException, a MyChecked, and a MyThrowable, which the Resource Leak Checker does not ignore. import java.io.*; import org.checkerframework.checker.calledmethods.qual.*; @@ -31,6 +31,9 @@ interface QuietCloseable extends Closeable { /** A checked exception that the Resource Leak Checker does not ignore. */ static class MyChecked extends Exception {} + /** A throwable that is not an Exception, and that the Resource Leak Checker does not ignore. */ + static class MyThrowable extends Throwable {} + public abstract void mightThrow() throws IOException; public abstract void mightThrowMyChecked() throws MyChecked; @@ -128,14 +131,14 @@ void closedOnOneExceptionalPath() throws MyChecked { } } - /** Closes r if it throws an Exception, but not if it throws a Throwable that is not one. */ + /** Closes r if it throws an Exception, but not if it throws a MyThrowable. */ @EnsuresCalledMethodsOnException(value = "#1", methods = "close") - public abstract void closeOnException(QuietCloseable r) throws IOException, Throwable; + public abstract void closeOnException(QuietCloseable r) throws IOException, MyThrowable; - void closedOnOneExceptionTypeFromOneNode() throws Throwable { - // One call throws an IOException after closing r, and a Throwable without closing r. The + void closedOnOneExceptionTypeFromOneNode() throws MyThrowable { + // One call throws an IOException after closing r, and a MyThrowable without closing r. The // IOException reaches the finally block while r is closed, and the first catch block returns. - // The Throwable reaches the finally block while r is open, and the second catch block closes + // The MyThrowable reaches the finally block while r is open, and the second catch block closes // r. So r is closed on every path. The finally block must not merge those two paths and then // throw the IOException while r is open. QuietCloseable r = allocQuietCloseable(); @@ -147,7 +150,7 @@ void closedOnOneExceptionTypeFromOneNode() throws Throwable { } } catch (IOException e) { return; - } catch (Throwable t) { + } catch (MyThrowable t) { r.close(); throw t; } @@ -168,4 +171,24 @@ void closedBeforeOtherExceptionToSameDestination() throws IOException, MyChecked log(); } } + + @Owning + Closeable successFlag() throws IOException { + // A false positive. The finally block closes c on every path on which an exception reaches it, + // because success is false on each such path. The Resource Leak Checker does not track the + // value of success, so it reports that c might be open when the finally block rethrows the + // IOException. + // :: error: [required.method.not.called] + Closeable c = alloc(); + boolean success = false; + try { + mightThrow(); + success = true; + return c; + } finally { + if (!success) { + c.close(); + } + } + } } diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 92296ea5a19f..d0c5101c4f54 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -1230,7 +1230,12 @@ \subsubsection{Handling \code{finally} blocks} same \code{catch} blocks, or the exit of the method) share a duplicate. Exception types that would be rethrown to different places get different duplicates, so that the analysis does not merge the stores of paths that -never meet. +never meet. Because nested \code{finally} blocks multiply the duplicates, +the Dataflow Framework bounds the number of nodes, in one control flow +graph, of the exceptional duplicates beyond the first for each +\code{finally} block. Once the bound is reached, the exception types that +do not yet have a duplicate share one duplicate, even if they would be +rethrown to different places. \subsection{AST to CFG Translation} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index bd042c5ae07d..c8c79faeec3b 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2919,13 +2919,14 @@ private void handleFinally( // grows exponentially with the depth of the nesting of finally blocks in finally blocks, with // a base that grows with the number of copies per finally block. // - // As an optimization, two types share a copy if and only if the copy rethrows them to the same - // places: the same catch blocks, or the exit, past any enclosing finally blocks. The analysis - // merges the stores of the paths that reach a copy. Types that go to different places get - // different copies, so that the analysis does not merge stores of paths that never meet. For - // example, the Resource Leak Checker would otherwise report a leak when an exception thrown - // while a resource is open is caught by a catch block that closes the resource, and another - // exception, thrown after the resource is closed, propagates out of the method. + // As an optimization, until the budget described below is used up, two types share a copy if + // and only if the copy rethrows them to the same places: the same catch blocks, or the exit, + // past any enclosing finally blocks. The analysis merges the stores of the paths that reach a + // copy. Types that go to different places get different copies, so that the analysis does not + // merge stores of paths that never meet. For example, the Resource Leak Checker would + // otherwise report a leak when an exception thrown while a resource is open is caught by a + // catch block that closes the resource, and another exception, thrown after the resource is + // closed, propagates out of the method. // // As a further optimization, to bound growth, once the copies beyond the first copy for each // finally block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index f1ac8cfed56b..270afd71ef4d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,13 @@ ### User-visible changes +The Resource Leak Checker no longer ignores an exception that propagates out +of a `finally` block, so it reports leaks that it formerly missed. It also +reports a false positive for a `finally` block that closes a resource only if +a boolean variable records that the `try` block did not complete, as in +`finally { if (!success) { c.close(); } }`, because it does not track the +value of the boolean variable. + ### Changes for type system implementers A default that a type system registers for an element through From b2469d0dd064fc1636cde39300936dab7ba58bd4 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 23 Nov 2026 20:50:03 -0800 Subject: [PATCH 67/98] Record exceptions from implicit toString() in string conversion and from throwing a nullable reference --- .../cfg/builder/CFGTranslationPhaseOne.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index f1d7666a1950..dcedf810e2b8 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1022,7 +1022,15 @@ protected Node stringConversion(Node node) { if (!TypesUtils.isString(node.getType())) { Node converted = new StringConversionNode(node.getTree(), node, stringType); addToImplicitlyConvertedLookupMap(converted); - insertNodeAfter(converted, node); + TypeMirror type = node.getType(); + if (type.getKind().isPrimitive() + || type.getKind() == TypeKind.NULL + || TypesUtils.isBoxedPrimitive(type)) { + insertNodeAfter(converted, node); + } else { + // The conversion may invoke an arbitrary toString() method, which may throw. + insertNodeWithExceptionsAfter(converted, uncheckedExceptionTypes, node); + } return converted; } else { return node; @@ -3499,7 +3507,19 @@ public Node visitThrow(ThrowTree tree, Void p) { Node expression = scan(tree.getExpression(), p); TypeMirror exception = expression.getType(); ThrowNode throwsNode = new ThrowNode(tree, expression, env.getTypeUtils()); - NodeWithExceptionsHolder exNode = extendWithNodeWithException(throwsNode, exception); + NodeWithExceptionsHolder exNode; + if (exception.getKind() == TypeKind.NULL) { + // `throw null` throws a NullPointerException (JLS 14.18). + exNode = extendWithNodeWithException(throwsNode, nullPointerExceptionType); + } else if (mayBeNull(expression)) { + // Throwing null throws a NullPointerException instead (JLS 14.18). + Set causes = new ArraySet<>(2); + causes.add(exception); + causes.add(nullPointerExceptionType); + exNode = extendWithNodeWithExceptions(throwsNode, causes); + } else { + exNode = extendWithNodeWithException(throwsNode, exception); + } exNode.setTerminatesExecution(true); return throwsNode; } From 4a096619944ec13379e3c7301ef1f6ae8b706c55 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 23 Nov 2026 20:52:47 -0800 Subject: [PATCH 68/98] Treat `throw null` as throwing NullPointerException in the CFG The null type reached TryCatchFrame.possibleLabels, which accepts only declared types and type variables. --- checker/tests/nullness/Exceptions.java | 20 +++++++++++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 5 +++++ 2 files changed, 25 insertions(+) diff --git a/checker/tests/nullness/Exceptions.java b/checker/tests/nullness/Exceptions.java index 4505730ef1b2..d9434fc7900e 100644 --- a/checker/tests/nullness/Exceptions.java +++ b/checker/tests/nullness/Exceptions.java @@ -44,4 +44,24 @@ void reassignException() { throw e; } } + + // `throw null` throws a NullPointerException. + void throwNullInTryCatch() { + try { + // :: error: [throwing.nullable] + throw null; + } catch (NullPointerException e) { + } + } + + void throwNullInTryFinallyInTryCatch() { + try { + try { + // :: error: [throwing.nullable] + throw null; + } finally { + } + } catch (IllegalStateException e) { + } + } } diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 820871a560fc..eea46a36f7eb 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -3415,6 +3415,11 @@ public Node visitReturn(ReturnTree tree, Void p) { public Node visitThrow(ThrowTree tree, Void p) { Node expression = scan(tree.getExpression(), p); TypeMirror exception = expression.getType(); + if (exception.getKind() == TypeKind.NULL) { + // `throw null` throws a NullPointerException (JLS 14.18). The null type must not reach + // TryCatchFrame.possibleLabels, which requires a declared type or a type variable. + exception = nullPointerExceptionType; + } ThrowNode throwsNode = new ThrowNode(tree, expression, env.getTypeUtils()); NodeWithExceptionsHolder exNode = extendWithNodeWithException(throwsNode, exception); exNode.setTerminatesExecution(true); From 6e720faed293fea22201099e37816fda0bb93b9c Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 25 Nov 2026 05:25:30 -0800 Subject: [PATCH 69/98] Test the shared exceptional finally copy after the budget is used up; clarify comments --- .../checker/mustcall/MustCallChecker.java | 7 +- checker/tests/nullness/FinallyCopyBudget.java | 103 ++++++++++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 37 ++++--- 3 files changed, 128 insertions(+), 19 deletions(-) create mode 100644 checker/tests/nullness/FinallyCopyBudget.java diff --git a/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java b/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java index d76af9fed56f..a965472436a2 100644 --- a/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java +++ b/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java @@ -64,8 +64,11 @@ public MustCallChecker() {} private static final SetOfTypes DEFAULT_IGNORED_EXCEPTIONS = SetOfTypes.anyOfTheseNames( ImmutableSet.of( - // Any method call has a CFG edge for Throwable/RuntimeException/Error - // to represent run-time misbehavior. Ignore it. + // Any method call has a CFG edge for RuntimeException and Error to represent + // run-time misbehavior. Ignore them. A CFG edge for exactly Throwable comes from + // code that throws a value of unknown exception type, such as a `throw` statement + // whose expression has static type Throwable or a call to a method whose `throws` + // clause names Throwable, such as `MethodHandle.invoke`. Ignore it too. Throwable.class.getCanonicalName(), Error.class.getCanonicalName(), RuntimeException.class.getCanonicalName(), diff --git a/checker/tests/nullness/FinallyCopyBudget.java b/checker/tests/nullness/FinallyCopyBudget.java new file mode 100644 index 000000000000..1845bcbb5dbe --- /dev/null +++ b/checker/tests/nullness/FinallyCopyBudget.java @@ -0,0 +1,103 @@ +// Tests the exceptional copy of a finally block that the CFG builder creates after the extra +// exceptional copies of earlier finally blocks in the same method have used up +// CFGTranslationPhaseOne.EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET. The exceptions that reach such a +// finally block share one exceptional copy of it, which must rethrow each of them to the place +// that it goes: here, a different catch block for each of IOException, RuntimeException, and +// Error. +// +// The nested finally blocks at the beginning of the method use up the budget. If the budget is +// increased, deepen their nesting so that they still use it up. + +import java.io.IOException; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; + +abstract class FinallyCopyBudget { + abstract void mightThrow() throws IOException; + + abstract void log(); + + void afterBudgetIsUsedUp() { + // These finally blocks use up the budget. Each of them has two exceptional copies: one + // rethrows IOException to the catch block, and the other rethrows RuntimeException and Error + // out of the method. Nesting makes the number of copies grow exponentially. + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + log(); + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + + // This finally block has one exceptional copy, which rethrows all three exceptions. The + // finally block and the catch blocks contain no method calls, so mightThrow() is the only + // source of the exceptions that the catch blocks catch. + @Nullable Object o = ""; + boolean finished = false; + try { + try { + try { + try { + o = null; + mightThrow(); + o = ""; + } finally { + finished = true; + } + } catch (IOException e) { + // :: error: (assignment) + @NonNull Object fromIOException = o; + } + } catch (RuntimeException e) { + // :: error: (assignment) + @NonNull Object fromRuntimeException = o; + } + } catch (Error e) { + // :: error: (assignment) + @NonNull Object fromError = o; + } + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index c276ce0a2777..114385a85b48 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -294,6 +294,9 @@ public class CFGTranslationPhaseOne extends TreeScanner { * finally block, and that rethrows the exception after the finally block completes normally. An * extra copy is one other than the first exceptional copy of a given finally block. See {@link * #handleFinally}. + * + *

The test {@code checker/tests/nullness/FinallyCopyBudget.java} uses up this budget. If you + * increase it, check that the test still uses it up. */ private static final int EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET = 10_000; @@ -2914,25 +2917,25 @@ private void handleFinally( // `groups` partitions the types of the exceptions that reach the finally block. For each // group, a copy of the finally block starts at the group's entry labels, which exceptions of // the group's types jump to when they reach the finally block, and the copy rethrows the - // group's types after the finally block completes normally. Types that go to the same places - // share a copy, because the analysis merges their stores there anyway. The number of copies - // grows exponentially with the depth of the nesting of finally blocks in finally blocks, with - // a base that grows with the number of copies per finally block. + // group's types after the finally block completes normally. // - // As an optimization, until the budget described below is used up, two types share a copy if - // and only if the copy rethrows them to the same places: the same catch blocks, or the exit, - // past any enclosing finally blocks. The analysis merges the stores of the paths that reach a - // copy. Types that go to different places get different copies, so that the analysis does not - // merge stores of paths that never meet. For example, the Resource Leak Checker would - // otherwise report a leak when an exception thrown while a resource is open is caught by a - // catch block that closes the resource, and another exception, thrown after the resource is - // closed, propagates out of the method. + // For precision, until the budget described below is used up, two types share a copy if and + // only if the copy rethrows them to the same places: the same catch blocks, or the exit, past + // any enclosing finally blocks. The analysis merges the stores of the paths that reach a copy. + // Types that go to the same places lose no precision by sharing a copy, because the analysis + // merges their stores at those places anyway. Types that go to different places get different + // copies, so that the analysis does not merge stores of paths that never meet. For example, + // the Resource Leak Checker would otherwise report a leak when an exception thrown while a + // resource is open is caught by a catch block that closes the resource, and another exception, + // thrown after the resource is closed, propagates out of the method. // - // As a further optimization, to bound growth, once the copies beyond the first copy for each - // finally block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that - // do not yet have a copy share a single copy, which rethrows each of their exceptions. A - // finally block that the CFG builder translates after that point has a single exceptional - // copy, which all of its groups share, as if all of its exceptions went to the same places. + // The number of copies grows exponentially with the depth of the nesting of finally blocks in + // finally blocks, with a base that grows with the number of copies per finally block. To + // bound that growth, once the copies beyond the first copy for each finally block have + // contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that do not yet have a + // copy share a single copy, which rethrows each of their exceptions. A finally block that the + // CFG builder translates after that point has a single exceptional copy, which all of its + // groups share, as if all of its exceptions went to the same places. List groups = new ArrayList<>(rethrowGroups(exceptionalFinallyFrame)); for (int i = 0; i < groups.size(); i++) { From dd11ae518e08f54e6eb6117ca4fb58cce85603f7 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 16:51:58 -0800 Subject: [PATCH 70/98] Compute each block's predecessors once in ControlFlowGraph.checkInvariants Block.getPredecessors takes time quadratic in the number of predecessors, and checkInvariants called it once per edge into the block. A block such as the exceptional exit can have thousands of predecessors. --- .../dataflow/cfg/ControlFlowGraph.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java index f4eded2d6802..f22652b9bce9 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/ControlFlowGraph.java @@ -151,6 +151,12 @@ public ControlFlowGraph( */ public void checkInvariants() { // TODO: this is a big data structure with many more invariants... + + // The predecessors of each block, computed once per block. Block.getPredecessors takes time + // quadratic in the number of predecessors, and a block such as the exceptional exit can have + // thousands of predecessors. + IdentityHashMap> predecessors = new IdentityHashMap<>(); + for (Block b : getAllBlocks()) { // Each node in the block should have this block as its parent. @@ -168,7 +174,9 @@ public void checkInvariants() { // Each successor should have this block in its predecessors. for (Block succ : b.getSuccessors()) { - if (!succ.getPredecessors().contains(b)) { + if (!predecessors + .computeIfAbsent(succ, s -> new HashSet<>(s.getPredecessors())) + .contains(b)) { throw new IllegalStateException( "Block " + b From 9fc422b263352a8d5f98720790a0db83e94d4408 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 17:06:00 -0800 Subject: [PATCH 71/98] Make FinallyCopyBudget fail if the budget is not used up; document the success-flag false positive The last finally block of FinallyCopyBudget.afterBudgetIsUsedUp now has an IOException path and a RuntimeException path with different stores, so its expected errors differ depending on whether IOException gets its own copy. The new method beforeBudgetIsUsedUp shows the separate-copy result. The Resource Leak Checker manual describes the false positive for a finally block that closes a resource only if a boolean flag records failure, and the catch-and-rethrow workaround. Sharing a copy of a finally block loses precision only for a transfer function that is more precise on separate stores than on their merge. Also clarify comments and Javadoc about exceptional copies of finally blocks. --- .../checker/mustcall/MustCallChecker.java | 10 ++-- checker/tests/nullness/FinallyCopyBudget.java | 47 ++++++++++++++-- dataflow/manual/content.tex | 4 +- .../cfg/builder/CFGTranslationPhaseOne.java | 56 ++++++++++--------- .../dataflow/cfg/builder/RethrowGroup.java | 38 +++++++------ .../dataflow/cfg/builder/TryFinallyFrame.java | 21 +++---- docs/CHANGELOG.md | 7 --- docs/manual/resource-leak-checker.tex | 46 +++++++++++++++ 8 files changed, 154 insertions(+), 75 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java b/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java index a965472436a2..0d28332bd968 100644 --- a/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java +++ b/checker/src/main/java/org/checkerframework/checker/mustcall/MustCallChecker.java @@ -64,11 +64,11 @@ public MustCallChecker() {} private static final SetOfTypes DEFAULT_IGNORED_EXCEPTIONS = SetOfTypes.anyOfTheseNames( ImmutableSet.of( - // Any method call has a CFG edge for RuntimeException and Error to represent - // run-time misbehavior. Ignore them. A CFG edge for exactly Throwable comes from - // code that throws a value of unknown exception type, such as a `throw` statement - // whose expression has static type Throwable or a call to a method whose `throws` - // clause names Throwable, such as `MethodHandle.invoke`. Ignore it too. + // Every method call has a CFG edge for RuntimeException and another for Error, to + // represent run-time misbehavior. Ignore them. A CFG edge for exactly Throwable + // comes from code that throws a value of unknown exception type, such as a `throw` + // statement whose expression has static type Throwable or a call to a method whose + // `throws` clause names Throwable, such as `MethodHandle.invoke`. Ignore it too. Throwable.class.getCanonicalName(), Error.class.getCanonicalName(), RuntimeException.class.getCanonicalName(), diff --git a/checker/tests/nullness/FinallyCopyBudget.java b/checker/tests/nullness/FinallyCopyBudget.java index 1845bcbb5dbe..f9a12dc1b7da 100644 --- a/checker/tests/nullness/FinallyCopyBudget.java +++ b/checker/tests/nullness/FinallyCopyBudget.java @@ -5,8 +5,10 @@ // that it goes: here, a different catch block for each of IOException, RuntimeException, and // Error. // -// The nested finally blocks at the beginning of the method use up the budget. If the budget is -// increased, deepen their nesting so that they still use it up. +// The nested finally blocks at the beginning of afterBudgetIsUsedUp() use up the budget. If they +// do not, the last finally block gets a separate copy for IOException, and the expected error in +// its catch block for IOException does not occur, so the test fails. In that case, deepen their +// nesting so that they use up the budget. import java.io.IOException; import org.checkerframework.checker.nullness.qual.NonNull; @@ -72,17 +74,21 @@ void afterBudgetIsUsedUp() { } catch (IOException e) { } - // This finally block has one exceptional copy, which rethrows all three exceptions. The - // finally block and the catch blocks contain no method calls, so mightThrow() is the only - // source of the exceptions that the catch blocks catch. + // This finally block has one exceptional copy, which rethrows all three exceptions. An + // IOException comes only from mightThrow(), when o is non-null. A RuntimeException or an Error + // also comes from log(), when o is null. The copy merges the stores of all those paths, so o + // might be null in each catch block, even the one for IOException. The finally block and the + // catch blocks contain no method calls, so mightThrow() and log() are the only sources of the + // exceptions that the catch blocks catch. @Nullable Object o = ""; boolean finished = false; try { try { try { try { - o = null; mightThrow(); + o = null; + log(); o = ""; } finally { finished = true; @@ -100,4 +106,33 @@ void afterBudgetIsUsedUp() { @NonNull Object fromError = o; } } + + void beforeBudgetIsUsedUp() { + // The same code as at the end of afterBudgetIsUsedUp(), but no earlier finally block uses up + // the budget. So IOException has its own copy of the finally block, in which o is non-null. + @Nullable Object o = ""; + boolean finished = false; + try { + try { + try { + try { + mightThrow(); + o = null; + log(); + o = ""; + } finally { + finished = true; + } + } catch (IOException e) { + @NonNull Object fromIOException = o; + } + } catch (RuntimeException e) { + // :: error: (assignment) + @NonNull Object fromRuntimeException = o; + } + } catch (Error e) { + // :: error: (assignment) + @NonNull Object fromError = o; + } + } } diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index d0c5101c4f54..92c8004c4391 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -1231,8 +1231,8 @@ \subsubsection{Handling \code{finally} blocks} Exception types that would be rethrown to different places get different duplicates, so that the analysis does not merge the stores of paths that never meet. Because nested \code{finally} blocks multiply the duplicates, -the Dataflow Framework bounds the number of nodes, in one control flow -graph, of the exceptional duplicates beyond the first for each +the Dataflow Framework bounds the number of nodes +of the exceptional duplicates beyond the first for each \code{finally} block. Once the bound is reached, the exception types that do not yet have a duplicate share one duplicate, even if they would be rethrown to different places. diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index cba12d3623d6..bfa8680be9d6 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -288,16 +288,16 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** * The maximum number of nodes in extra exceptional copies of finally blocks. Once the extra - * copies contain this many nodes, the exception types that reach a finally block and do not yet - * have a copy share one exceptional copy of that finally block, so a finally block that the CFG - * builder translates after that point has only one exceptional copy. An exceptional copy of a - * finally block is a translation of the finally block that runs when an exception reaches the - * finally block, and that rethrows the exception after the finally block completes normally. An - * extra copy is one other than the first exceptional copy of a given finally block. See {@link - * #handleFinally}. + * copies contain this many nodes, new exception types that reach a finally block share one + * exceptional copy of that finally block. * - *

The test {@code checker/tests/nullness/FinallyCopyBudget.java} uses up this budget. If you - * increase it, check that the test still uses it up. + *

An exceptional copy of a finally block is a translation of the finally block that runs when + * an exception reaches the finally block, and that rethrows the exception after the finally block + * completes normally. An extra copy is one other than the first exceptional copy of a given + * finally block. See {@link #handleFinally}. + * + *

The test {@code checker/tests/nullness/FinallyCopyBudget.java} uses up this budget, and it + * fails if it does not use up the budget. */ private static final int EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET = 10_000; @@ -2920,31 +2920,34 @@ private void handleFinally( extendWithExtendedNode(new UnconditionalJump(doneLabel)); } - // `groups` partitions the types of the exceptions that reach the finally block. For each - // group, a copy of the finally block starts at the group's entry labels, which exceptions of - // the group's types jump to when they reach the finally block, and the copy rethrows the - // group's types after the finally block completes normally. + // `groups` partitions the types of the exceptions that the try block and the catch blocks + // throw to this finally block (the one that `finallyBlockCFGGenerator` generates), that is, + // the exceptions that reach `exceptionalFinallyFrame`. For each group, a copy of this + // finally block starts at the group's entry labels, which exceptions of the group's types + // jump to when they reach this finally block, and the copy rethrows the group's types after + // this finally block completes normally. // - // For precision, until the budget described below is used up, two types share a copy if and - // only if the copy rethrows them to the same places: the same catch blocks, or the exit, past - // any enclosing finally blocks. The analysis merges the stores of the paths that reach a copy. - // Types that go to the same places lose no precision by sharing a copy, because the analysis - // merges their stores at those places anyway. Types that go to different places get different + // For precision, until the EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET budget is used up, two types + // share a copy if and only if the copy rethrows them to the same places. The analysis merges + // the stores of the paths that reach a copy. Types that go to the same places lose little + // precision by sharing a copy, because the analysis merges their stores at those places anyway. + // Sharing a copy merges the stores before the finally block rather than after it, which loses + // precision only if a transfer function in the finally block yields more precise results on + // the separate stores than on their merge. Types that go to different places get different // copies, so that the analysis does not merge stores of paths that never meet. For example, // the Resource Leak Checker would otherwise report a leak when an exception thrown while a // resource is open is caught by a catch block that closes the resource, and another exception, // thrown after the resource is closed, propagates out of the method. // // The number of copies grows exponentially with the depth of the nesting of finally blocks in - // finally blocks, with a base that grows with the number of copies per finally block. To - // bound that growth, once the copies beyond the first copy for each finally block have - // contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that do not yet have a - // copy share a single copy, which rethrows each of their exceptions. A finally block that the - // CFG builder translates after that point has a single exceptional copy, which all of its - // groups share, as if all of its exceptions went to the same places. + // finally blocks. To bound that growth, once the copies beyond the first copy for each finally + // block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that do not + // yet have a copy share a single copy, which rethrows each of their exceptions. List groups = new ArrayList<>(rethrowGroups(exceptionalFinallyFrame)); for (int i = 0; i < groups.size(); i++) { + // Making the previous copies, and the copies of finally blocks nested in them, might have + // used up the budget. This merges groups, before finally blocks are created for them. if (i < groups.size() - 1 && extraExceptionalFinallyNodes >= EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET) { List remainingGroups = groups.subList(i, groups.size()); @@ -3117,9 +3120,8 @@ private void handleFinally( * TryStack#possibleLabelsPastFinally} returns the same set of labels for each of them. * * @param frame a frame for a finally block, which the CFG builder has popped from the try stack - * @return the groups, in a deterministic order: the order in which the first type of each group - * reaches {@code frame} (see {@link TryFinallyFrame#getExceptionLabels}); the entry label of - * each type is its label in {@code frame}. Empty if no exception reaches {@code frame}. + * @return the groups, in a deterministic order; the entry label of each type is its label in + * {@code frame}. Empty if no exception reaches {@code frame}. */ private Collection rethrowGroups(TryFinallyFrame frame) { Map, RethrowGroup> groups = new LinkedHashMap<>(); diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java index c933515fae84..abd2ad044a7a 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java @@ -9,20 +9,25 @@ import org.plumelib.util.ArrayMap; /** - * Some of the types of the exceptions that reach a finally block (as defined in the documentation - * of {@link TryFinallyFrame}), such as {@code java.io.IOException} and {@code - * java.lang.RuntimeException}, all of which one copy of the finally block rethrows after the - * finally block completes normally. Each type has an entry label: the label that an exception of - * the type jumps to when it reaches the finally block (see {@link - * TryFinallyFrame#getExceptionLabels}). The copy starts at the entry labels of all the types in its - * group. + * A set of exception types that share one exceptional copy of a finally block. + * + *

An exceptional copy of a finally block runs when an exception reaches the finally block (as + * defined in the documentation of {@link TryFinallyFrame}), and it rethrows the exception after the + * finally block completes normally. The types in a group, such as {@code java.io.IOException} and + * {@code java.lang.RuntimeException}, are some of the types of the exceptions that reach the + * finally block. + * + *

For each of its types, a group stores the type's entry label: the label that the finally + * block's {@link TryFinallyFrame} sends the type to, which is the target of the exceptional edges + * for the type. The {@link TryFinallyFrame} creates the label (see {@link + * TryFinallyFrame#getExceptionLabels}), and the group stores a reference to the same label. The + * group's copy starts at the entry labels of all the types in the group. */ /*package-private*/ final class RethrowGroup { /** - * The entry label of each type in this group, in a deterministic order: the order in which the - * types first reach the finally block. Like the map in {@link TryFinallyFrame}, it contains few - * entries. + * For each type in this group, its entry label. Like the map in {@link TryFinallyFrame}, it + * contains few entries. */ private final Map entryLabels = new ArrayMap<>(); @@ -30,11 +35,12 @@ /*package-private*/ RethrowGroup() {} /** - * Adds the given type to this group. + * Adds the given type and label to this group. * * @param type a type of exception that reaches the finally block and is not in this group - * @param entryLabel the label that an exception of type {@code type} jumps to when it reaches the - * finally block + * @param entryLabel the label that the finally block's {@link TryFinallyFrame} sends {@code type} + * to: the target of the exceptional edges for {@code type} (see {@link + * TryFinallyFrame#getExceptionLabels}) */ /*package-private*/ void add(TypeMirror type, Label entryLabel) { entryLabels.put(type, entryLabel); @@ -61,9 +67,9 @@ /** * Returns a new group that contains every type in the given groups. * - * @param groups a list of groups for the same finally block, no two of which contain the same - * type - * @return a new group that contains every type in {@code groups}, in the order of {@code groups} + * @param groups a list of groups for the same finally block; no type is in more than one of the + * groups + * @return a new group that contains every type in {@code groups}, in a deterministic order */ /*package-private*/ static RethrowGroup merge(List groups) { RethrowGroup result = new RethrowGroup(); diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java index 9f55ce42bd60..21ef9c2f4e71 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java @@ -28,12 +28,12 @@ /** * A label for each type of exception that reaches this frame (as defined in the documentation of - * {@link TryFinallyFrame}). No two keys are the same type according to {@link Types#isSameType}, - * even if {@link TypeMirror#equals} would distinguish them. + * {@link TryFinallyFrame}). No two keys are the same type according to {@link Types#isSameType}. + * {@link TypeMirror#equals} is not a reliable test, because two {@code TypeMirror} objects that + * represent the same type can be unequal; therefore, look up a type by comparing it to each key + * with {@link Types#isSameType}, not with {@link Map#get}. * - *

The keys are in a deterministic order: the order in which the CFG builder first creates a - * node that throws the type to this frame. Any deterministic order would do; it makes the CFG, - * such as the order of the copies of the finally block, the same on every run. + *

The keys are in a deterministic order, so the CFG is the same on every run. * *

The map contains few entries, usually only a handful, so it is an {@link ArrayMap}. The * types that reach a frame are {@code java.lang.RuntimeException} and {@code java.lang.Error}, @@ -49,7 +49,7 @@ /** * Constructs a TryFinallyFrame. * - * @param types a {@link Types}, used to give each type of exception a single label + * @param types a type utility object */ public TryFinallyFrame(Types types) { this.types = types; @@ -67,7 +67,7 @@ public boolean possibleLabels(TypeMirror thrown, Set

The receiver remains unrefined on the other exceptional successors. That loses no precision - * for an invocation in source code, because its {@code NullPointerException} for a null receiver - * comes from its {@code MethodAccessNode}, and every handler that such an edge of {@code n} - * reaches also catches that {@code NullPointerException}. But it is necessary for a synthetic - * invocation, such as the {@code iterator()} call of an enhanced {@code for} loop, which can - * throw that {@code NullPointerException} itself. + *

For an invocation in source code, the receiver is non-null on every exceptional successor. + * Its {@code NullPointerException} for a null receiver comes from its {@code MethodAccessNode}, + * not from {@code n}. So every exception that {@code n} throws comes from the invoked method, + * which the invocation entered only because the receiver is non-null. A handler that the {@code + * MethodAccessNode}'s {@code NullPointerException} edge reaches, such as a handler for {@code + * NullPointerException} or {@code RuntimeException}, merges in the unrefined store from that + * edge, so the receiver is not non-null there. + * + *

For a synthetic invocation, the receiver is non-null only on each exceptional successor + * whose exception type excludes {@code NullPointerException}, such as a handler for a checked + * exception that the invoked method declares. A synthetic invocation, such as the {@code + * iterator()} call of an enhanced {@code for} loop, can throw the {@code NullPointerException} + * for a null receiver itself. * * @param n a method invocation whose receiver should be refined * @param result the transfer result for {@code n} @@ -551,8 +565,9 @@ private TransferResult refineReceiverOnExceptional Map newExceptionalStores = oldExceptionalStores == null ? new HashMap<>() : new HashMap<>(oldExceptionalStores); boolean refined = false; + boolean isInSource = n.getInSource(); for (TypeMirror exceptionType : exceptionBlock.getExceptionalSuccessors().keySet()) { - if (analysis.getTypes().isSubtype(nullPointerExceptionType, exceptionType)) { + if (!isInSource && analysis.getTypes().isSubtype(nullPointerExceptionType, exceptionType)) { continue; } NullnessStore exceptionalStore = newExceptionalStores.get(exceptionType); @@ -576,7 +591,11 @@ private TransferResult refineReceiverOnExceptional * side-effect-free. * *

Matching a record pattern, as in {@code o instanceof R(int i)}, implicitly invokes the - * record's component accessors. This method handles them as it handles explicit method + * record's component accessors. Likewise, string conversion implicitly invokes {@code + * toString()}, a try-with-resources statement implicitly invokes {@code close()}, and an enhanced + * {@code for} loop over an {@code Iterable} implicitly invokes {@code iterator()}, {@code + * hasNext()}, and {@code next()}. (An argument can contain a statement within a switch + * expression.) This method handles these implicit invocations as it handles explicit method * invocations. * *

This method does not examine the bodies of lambda expressions and anonymous classes in the @@ -593,12 +612,9 @@ private boolean argumentsMayReassign( if (arguments.isEmpty()) { return false; } - // A method call's value can depend on state that does not appear in the expression, such as a - // static field that the method reads. (MethodCall.isAssignableByOtherCode() examines only the - // receiver and arguments.) So, an assignment to a non-local variable or a call with side - // effects might change the value of a receiver that contains a method call. - boolean receiverMayChangeByOtherCode = - receiverExpr.isAssignableByOtherCode() || receiverExpr.containsOfClass(MethodCall.class); + // An assignment to a non-local variable or a call with side effects might change the value of + // a receiver that is assignable by other code or that contains a method call. + boolean receiverMayChangeByOtherCode = mayChangeByOtherCode(receiverExpr); TreeScanner scanner = new TreeScanner() { @Override @@ -613,11 +629,15 @@ public Boolean visitAssignment(AssignmentTree tree, Void p) { @Override public Boolean visitCompoundAssignment(CompoundAssignmentTree tree, Void p) { - // `s += o`, for a String variable s, implicitly invokes o.toString(). + // `s += o` is string concatenation if either operand is a String. It implicitly + // invokes toString() on an operand that is not a String: on o for a String variable + // s, and on the old value of s for an Object variable s and a String o. return assignsReceiver(tree.getVariable()) || (tree.getKind() == Tree.Kind.PLUS_ASSIGNMENT - && TypesUtils.isString(TreeUtils.typeOf(tree.getVariable())) - && stringConversionMayHaveSideEffect(tree.getExpression())) + && (TypesUtils.isString(TreeUtils.typeOf(tree.getVariable())) + || TypesUtils.isString(TreeUtils.typeOf(tree.getExpression()))) + && (stringConversionMayHaveSideEffect(tree.getVariable()) + || stringConversionMayHaveSideEffect(tree.getExpression()))) || super.visitCompoundAssignment(tree, p); } @@ -669,6 +689,43 @@ && recordPatternMayHaveSideEffect(tree)) { return super.scan(tree, p); } + // A try-with-resources statement implicitly invokes close() on each resource. + @Override + public Boolean visitTry(TryTree tree, Void p) { + for (Tree resource : tree.getResources()) { + // A resource is a variable declaration or an expression. The type of a variable + // declaration tree is the type of the variable. + if (noArgMethodMayHaveSideEffect(TreeUtils.typeOf(resource), "close", null)) { + return true; + } + } + return super.visitTry(tree, p); + } + + // An enhanced for loop over an Iterable implicitly invokes iterator(), hasNext(), and + // next(). A loop over an array invokes no method. + @Override + public Boolean visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { + TypeMirror iterableType = TreeUtils.typeOf(tree.getExpression()); + // If mayHaveUnknownSideEffect() is false, then so is mayHaveSideEffect() for every + // method. + if (iterableType.getKind() != TypeKind.ARRAY && mayHaveUnknownSideEffect()) { + List iteratorMethods = noArgMethods(iterableType, "iterator"); + if (iteratorMethods.isEmpty()) { + return true; + } + for (ExecutableElement iteratorMethod : iteratorMethods) { + TypeMirror iteratorType = iteratorMethod.getReturnType(); + if (mayHaveSideEffect(iteratorMethod) + || noArgMethodMayHaveSideEffect(iteratorType, "hasNext", null) + || noArgMethodMayHaveSideEffect(iteratorType, "next", null)) { + return true; + } + } + } + return super.visitEnhancedForLoop(tree, p); + } + // visitMethodInvocation and visitNewClass handle the invocations that execute the body // of a lambda expression or anonymous class. @@ -714,7 +771,7 @@ private boolean assignsReceiver(ExpressionTree variable) { private boolean recordPatternMayHaveSideEffect(Tree recordPattern) { TypeElement recordElement = TypesUtils.getTypeElement(TreeUtils.typeOf(recordPattern)); if (recordElement == null) { - return receiverMayChangeByOtherCode && !nonNullAssumptionAfterInvocation; + return mayHaveUnknownSideEffect(); } for (RecordComponentElement component : recordElement.getRecordComponents()) { if (mayHaveSideEffect(component.getAccessor())) { @@ -739,25 +796,78 @@ private boolean stringConversionMayHaveSideEffect(ExpressionTree operand) { || TypesUtils.isString(type)) { return false; } + // An interface need not declare or inherit a toString() method, and an array type has + // no type element. + return noArgMethodMayHaveSideEffect(type, "toString", objectToString); + } + + /* + * Returns true if implicitly invoking the no-argument method with the given name on a + * value of the given static type might reassign the receiver. As for an explicit + * invocation, uses the methods of the static type. + * + * @param type the static type of the receiver of the implicit invocation + * @param name the name of the invoked method + * @param fallback the method that is invoked if {@code type} has no such method, or null + * if it is not known + * @return true if the implicit invocation might reassign the receiver + */ + private boolean noArgMethodMayHaveSideEffect( + TypeMirror type, String name, @Nullable ExecutableElement fallback) { + if (!mayHaveUnknownSideEffect()) { + // mayHaveSideEffect returns false for every method. + return false; + } + List methods = noArgMethods(type, name); + if (methods.isEmpty()) { + return fallback == null ? mayHaveUnknownSideEffect() : mayHaveSideEffect(fallback); + } + for (ExecutableElement m : methods) { + if (mayHaveSideEffect(m)) { + return true; + } + } + return false; + } + + /* + * Returns the no-argument methods with the given name that are members of the erasure + * of the given type, omitting each method that another of them overrides. (The + * checker requires an overriding method to be at least as pure as the method it + * overrides.) Returns more than one method if the type inherits several of them, which + * is conservative. Returns an empty list if the erasure has no type element, as for an + * array type. + * + * @param type a type + * @param name a method name + * @return the most specific no-argument methods named {@code name} in {@code type} + */ + private List noArgMethods(TypeMirror type, String name) { TypeElement typeElement = TypesUtils.getTypeElement(analysis.getTypes().erasure(type)); if (typeElement == null) { - // For example, an array type. - return mayHaveSideEffect(objectToString); + return List.of(); } - // As for an explicit invocation, use the toString() methods of the static type. - // getAllMethodsIn also returns overridden methods, which is conservative. - boolean foundToString = false; - for (ExecutableElement m : - ElementUtils.getAllMethodsIn(typeElement, nullnessTypeFactory.getElementUtils())) { - if (m.getSimpleName().contentEquals("toString") && m.getParameters().isEmpty()) { - foundToString = true; - if (mayHaveSideEffect(m)) { - return true; + Elements elements = nullnessTypeFactory.getElementUtils(); + List candidates = new ArrayList<>(); + for (ExecutableElement m : ElementUtils.getAllMethodsIn(typeElement, elements)) { + if (m.getSimpleName().contentEquals(name) && m.getParameters().isEmpty()) { + candidates.add(m); + } + } + List result = new ArrayList<>(); + for (ExecutableElement m : candidates) { + boolean isOverridden = false; + for (ExecutableElement other : candidates) { + if (!other.equals(m) && elements.overrides(other, m, typeElement)) { + isOverridden = true; + break; } } + if (!isOverridden) { + result.add(m); + } } - // An interface need not declare or inherit a toString() method. - return !foundToString && mayHaveSideEffect(objectToString); + return result; } /* @@ -767,9 +877,16 @@ private boolean stringConversionMayHaveSideEffect(ExpressionTree operand) { * @return true if invoking {@code executable} might reassign the receiver */ private boolean mayHaveSideEffect(ExecutableElement executable) { - return receiverMayChangeByOtherCode - && !nonNullAssumptionAfterInvocation - && !atypeFactory.isSideEffectFree(executable); + return mayHaveUnknownSideEffect() && !atypeFactory.isSideEffectFree(executable); + } + + /* + * Returns true if invoking a method that is not known might reassign the receiver. + * + * @return true if invoking a method that is not known might reassign the receiver + */ + private boolean mayHaveUnknownSideEffect() { + return receiverMayChangeByOtherCode && !nonNullAssumptionAfterInvocation; } }; for (ExpressionTree argument : arguments) { @@ -780,6 +897,20 @@ private boolean mayHaveSideEffect(ExecutableElement executable) { return false; } + /** + * Returns true if code other than an assignment to the given expression (or to a subexpression of + * it) might change the expression's value. That is the case if the expression is assignable by + * other code or contains a method call. A method call's value can depend on state that does not + * appear in the expression, such as a static field that the method reads. ({@link + * MethodCall#isAssignableByOtherCode()} examines only the receiver and arguments.) + * + * @param expr an expression + * @return true if code other than an assignment to {@code expr} might change its value + */ + private static boolean mayChangeByOtherCode(JavaExpression expr) { + return expr.isAssignableByOtherCode() || expr.containsOfClass(MethodCall.class); + } + /** * Returns true if {@code mapOrSubtype}'s value type (the V type argument to Map) is @Nullable. * diff --git a/checker/tests/nullness/ReceiverDependsOnStaticField.java b/checker/tests/nullness/ReceiverDependsOnStaticField.java index b2a3a5b7cf37..162b045ccf7d 100644 --- a/checker/tests/nullness/ReceiverDependsOnStaticField.java +++ b/checker/tests/nullness/ReceiverDependsOnStaticField.java @@ -25,4 +25,30 @@ void directAssignment() { // :: error: (dereference.of.nullable) current().toString(); } + + void clearSlot() { + slot = null; + } + + void acceptNonNull(Object o) {} + + // The invoked method is not side-effect-free and might write the static field, so normal + // completion of the call does not show that the receiver is non-null afterward. + // These tests do not first test `current()` against null: the store retains a refinement of a + // static call with no modifiable argument, such as `current()`, across a call that is not + // side-effect-free (see sideeffectsonly/StaticPureCallRefinement.java). + void sideEffectingCallNoArguments() { + // :: error: (dereference.of.nullable) + current().clearSlot(); + // :: error: (dereference.of.nullable) + current().toString(); + } + + // Likewise for an argument passed to a non-null parameter. + void sideEffectingCallNonNullArgument() { + // :: error: (argument) + acceptNonNull(current()); + // :: error: (dereference.of.nullable) + current().toString(); + } } diff --git a/checker/tests/nullness/ReceiverReassignedInArgument.java b/checker/tests/nullness/ReceiverReassignedInArgument.java index ebb4a26177be..233683c3d92e 100644 --- a/checker/tests/nullness/ReceiverReassignedInArgument.java +++ b/checker/tests/nullness/ReceiverReassignedInArgument.java @@ -78,10 +78,13 @@ void noReassignment(@Nullable Object q) { q.toString(); } - // A toString() method that reassigns the field f. + // A toString() method that reassigns the field f. It overrides Object.toString(), which is + // annotated @SideEffectFree, and purity annotations are inherited. So the Checker Framework + // reports the field assignment and treats Mutator.toString() as side-effect-free elsewhere. class Mutator { @Override public String toString() { + // :: error: (purity.assign.field) f = null; return ""; } @@ -95,19 +98,18 @@ public String toString() { } } - // String concatenation implicitly invokes Mutator.toString(), which reassigns f. + // String concatenation implicitly invokes Mutator.toString(). The checker trusts its inherited + // @SideEffectFree annotation (and reports the violation at its declaration), so f is refined. void stringConcatenationInArgument(Mutator m) { // :: error: (dereference.of.nullable) f.sefTake("" + m); - // :: error: (dereference.of.nullable) f.toString(); } - // `s += m` implicitly invokes Mutator.toString(), which reassigns f. + // `s += m` implicitly invokes Mutator.toString(), which the checker treats as side-effect-free. void stringCompoundAssignmentInArgument(Mutator m, String s) { // :: error: (dereference.of.nullable) f.sefTake(s += m); - // :: error: (dereference.of.nullable) f.toString(); } diff --git a/checker/tests/nullness/ReceiverRefinementInCatch.java b/checker/tests/nullness/ReceiverRefinementInCatch.java index aa63d2898607..8f26f2a5197e 100644 --- a/checker/tests/nullness/ReceiverRefinementInCatch.java +++ b/checker/tests/nullness/ReceiverRefinementInCatch.java @@ -39,6 +39,32 @@ void checkedAndRuntimeExceptionHandlers(@Nullable ReceiverRefinementInCatch r) { } } + void run() {} + + // A null receiver causes a NullPointerException at the method lookup, which a handler for + // IllegalArgumentException does not catch. An IllegalArgumentException comes from the invoked + // method, so the receiver is non-null in that handler. + void uncheckedExceptionHandler(@Nullable ReceiverRefinementInCatch r) { + try { + // :: error: (dereference.of.nullable) + r.run(); + } catch (IllegalArgumentException e) { + r.toString(); + } + } + + void runtimeExceptionSubtypeAndNullPointerExceptionHandlers(@Nullable Object o) { + try { + // :: error: (dereference.of.nullable) + o.toString(); + } catch (IllegalArgumentException e) { + o.hashCode(); + } catch (NullPointerException e) { + // :: error: (dereference.of.nullable) + o.hashCode(); + } + } + // An Error handler cannot catch the NullPointerException either. void errorHandler(@Nullable Object o) { try { @@ -116,6 +142,18 @@ void argumentDecrementsReceiverIndex(@Nullable ReceiverRefinementInCatch[] a, in a[i].toString(); } + @org.checkerframework.dataflow.qual.SideEffectFree + static void sefUse(Object o, int x) {} + + // A later argument reassigns a variable in the index of an earlier argument, so afterward + // a[i & 1] denotes a different array element. + void argumentReassignsIndexOfEarlierArgument(@Nullable Object[] a, int i) { + // :: error: (argument) + sefUse(a[i & 1], i = 1); + // :: error: (dereference.of.nullable) + a[i & 1].toString(); + } + void argumentDoesNotReassignReceiver(@Nullable Object o, @Nullable Object other) { // :: error: (dereference.of.nullable) o.equals(other = null); diff --git a/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java new file mode 100644 index 000000000000..ee11a42c1224 --- /dev/null +++ b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java @@ -0,0 +1,202 @@ +// @below-java17-jdk-skip-test + +import java.util.Iterator; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.SideEffectFree; + +// An argument that contains a switch expression can implicitly invoke methods: close() for a +// try-with-resources statement, and iterator(), hasNext(), and next() for an enhanced for loop. +// If such a method might reassign the receiver expression, then normal completion of the call +// does not show that the receiver expression is non-null afterward. +public class ReceiverReassignedByImplicitCall { + + @Nullable ReceiverReassignedByImplicitCall f; + + @SideEffectFree + void take(int i) {} + + class ClearingResource implements AutoCloseable { + @Override + public void close() { + f = null; + } + } + + class PureResource implements AutoCloseable { + @Override + @SideEffectFree + public void close() {} + } + + void resourceCloseClearsReceiver(int tag) { + ClearingResource resource = new ClearingResource(); + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + try (resource) {} + yield 0; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } + + void resourceDeclarationCloseClearsReceiver(int tag) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + try (ClearingResource resource = new ClearingResource()) {} + yield 0; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } + + void resourceCloseIsPure(int tag) { + PureResource resource = new PureResource(); + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + try (resource) {} + yield 0; + } + }); + f.toString(); + } + + // A try statement without resources invokes no method. + void tryWithoutResources(int tag) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + try { + } finally { + } + yield 0; + } + }); + f.toString(); + } + + // The iterator() method of an arbitrary Iterable might reassign f. + void iterableMightClearReceiver(int tag, Iterable iterable) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + for (Object ignored : iterable) {} + yield 0; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } + + class ClearingIterable implements Iterable { + @Override + public Iterator iterator() { + f = null; + return new java.util.ArrayList().iterator(); + } + } + + void iteratorClearsReceiver(int tag, ClearingIterable iterable) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + for (Object ignored : iterable) {} + yield 0; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } + + // Iterator.hasNext() is side-effect-free, and purity annotations are inherited. So the Checker + // Framework reports the field assignment in hasNext() and treats BaseIterator.hasNext() as + // side-effect-free elsewhere. Iterator.next() is not side-effect-free. + abstract class BaseIterator implements Iterator { + @Override + public boolean hasNext() { + // :: error: (purity.assign.field) + f = null; + return false; + } + + @Override + public Object next() { + f = null; + return ""; + } + } + + abstract class PureIterator extends BaseIterator { + @Override + @SideEffectFree + public boolean hasNext() { + return false; + } + + @Override + @SideEffectFree + public Object next() { + return ""; + } + } + + abstract class PureItems implements Iterable { + @Override + @SideEffectFree + public abstract PureIterator iterator(); + } + + abstract class ClearingItems implements Iterable { + @Override + @SideEffectFree + public abstract BaseIterator iterator(); + } + + void iteratorIsPure(int tag, PureItems items) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + for (Object ignored : items) {} + yield 0; + } + }); + f.toString(); + } + + // BaseIterator.next() might reassign f. + void nextClearsReceiver(int tag, ClearingItems items) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + for (Object ignored : items) {} + yield 0; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } + + void arrayLoop(int tag, Object[] array) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + for (Object ignored : array) {} + yield 0; + } + }); + f.toString(); + } +} diff --git a/checker/tests/resourceleak/ReceiverNullBeforeDispatch.java b/checker/tests/resourceleak-npenotignored/ReceiverNullBeforeDispatch.java similarity index 70% rename from checker/tests/resourceleak/ReceiverNullBeforeDispatch.java rename to checker/tests/resourceleak-npenotignored/ReceiverNullBeforeDispatch.java index b29abce872b6..0c130908607f 100644 --- a/checker/tests/resourceleak/ReceiverNullBeforeDispatch.java +++ b/checker/tests/resourceleak-npenotignored/ReceiverNullBeforeDispatch.java @@ -1,6 +1,7 @@ // A call tests its receiver for nullness after evaluating its arguments, but before the method // runs. So a handler for the NullPointerException that a null receiver causes must not assume the -// method's exceptional postconditions. +// method's exceptional postconditions. This test runs with an ignored-exceptions list that omits +// NullPointerException, so the Resource Leak Checker analyzes the edge to the handler. import java.io.*; import org.checkerframework.checker.calledmethods.qual.*; @@ -21,15 +22,4 @@ static void nullableReceiver(ReceiverNullBeforeDispatch r) throws IOException { } c.close(); } - - void thisReceiver() throws IOException { - // `this` is never null, so the handler is reached only if closeOnException throws. - Closeable c = new FileInputStream("file.txt"); - try { - this.closeOnException(c); - } catch (NullPointerException e) { - return; - } - c.close(); - } } diff --git a/checker/tests/resourceleak/ReceiverNullBeforeDispatchThis.java b/checker/tests/resourceleak/ReceiverNullBeforeDispatchThis.java new file mode 100644 index 000000000000..4ee6671afaae --- /dev/null +++ b/checker/tests/resourceleak/ReceiverNullBeforeDispatchThis.java @@ -0,0 +1,23 @@ +// A call tests its receiver for nullness after evaluating its arguments, but before the method +// runs. A receiver that is never null causes no NullPointerException, so a handler is reached only +// if the method throws. See also resourceleak-npenotignored/ReceiverNullBeforeDispatch.java. + +import java.io.*; +import org.checkerframework.checker.calledmethods.qual.*; + +abstract class ReceiverNullBeforeDispatchThis { + + @EnsuresCalledMethodsOnException(value = "#1", methods = "close") + abstract void closeOnException(Closeable c); + + void thisReceiver() throws IOException { + // `this` is never null, so the handler is reached only if closeOnException throws. + Closeable c = new FileInputStream("file.txt"); + try { + this.closeOnException(c); + } catch (NullPointerException e) { + return; + } + c.close(); + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 260e16e59b1e..f77498238e26 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -3523,19 +3523,7 @@ public Node visitThrow(ThrowTree tree, Void p) { exception = nullPointerExceptionType; } ThrowNode throwsNode = new ThrowNode(tree, expression, env.getTypeUtils()); - NodeWithExceptionsHolder exNode; - if (exception.getKind() == TypeKind.NULL) { - // `throw null` throws a NullPointerException (JLS 14.18). - exNode = extendWithNodeWithException(throwsNode, nullPointerExceptionType); - } else if (mayBeNull(expression)) { - // Throwing null throws a NullPointerException instead (JLS 14.18). - Set causes = new ArraySet<>(2); - causes.add(exception); - causes.add(nullPointerExceptionType); - exNode = extendWithNodeWithExceptions(throwsNode, causes); - } else { - exNode = extendWithNodeWithException(throwsNode, exception); - } + NodeWithExceptionsHolder exNode = extendWithNodeWithException(throwsNode, exception); exNode.setTerminatesExecution(true); return throwsNode; } From bfaa9038486cc6f7afd8f49e03da9d8b86516474 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 28 Nov 2026 23:06:09 -0800 Subject: [PATCH 76/98] Check that each catch block is reached; clarify finally-block documentation --- checker/tests/nullness/FinallyCopyBudget.java | 19 +++++++++++++++---- dataflow/manual/content.tex | 19 ++++++++++++------- .../cfg/builder/CFGTranslationPhaseOne.java | 7 ++++--- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/checker/tests/nullness/FinallyCopyBudget.java b/checker/tests/nullness/FinallyCopyBudget.java index f9a12dc1b7da..253cba334527 100644 --- a/checker/tests/nullness/FinallyCopyBudget.java +++ b/checker/tests/nullness/FinallyCopyBudget.java @@ -80,8 +80,13 @@ void afterBudgetIsUsedUp() { // might be null in each catch block, even the one for IOException. The finally block and the // catch blocks contain no method calls, so mightThrow() and log() are the only sources of the // exceptions that the catch blocks catch. + // + // The finally block sets p to a non-null value, so p is non-null in each catch block. This + // checks that the copy rethrows each exception to its catch block: if a catch block were + // unreachable, p would have its declared type, @Nullable, there, and the assignment of p would + // be an error. (The assignment of o would be an error in either case.) @Nullable Object o = ""; - boolean finished = false; + @Nullable Object p = null; try { try { try { @@ -91,19 +96,22 @@ void afterBudgetIsUsedUp() { log(); o = ""; } finally { - finished = true; + p = ""; } } catch (IOException e) { // :: error: (assignment) @NonNull Object fromIOException = o; + @NonNull Object pFromIOException = p; } } catch (RuntimeException e) { // :: error: (assignment) @NonNull Object fromRuntimeException = o; + @NonNull Object pFromRuntimeException = p; } } catch (Error e) { // :: error: (assignment) @NonNull Object fromError = o; + @NonNull Object pFromError = p; } } @@ -111,7 +119,7 @@ void beforeBudgetIsUsedUp() { // The same code as at the end of afterBudgetIsUsedUp(), but no earlier finally block uses up // the budget. So IOException has its own copy of the finally block, in which o is non-null. @Nullable Object o = ""; - boolean finished = false; + @Nullable Object p = null; try { try { try { @@ -121,18 +129,21 @@ void beforeBudgetIsUsedUp() { log(); o = ""; } finally { - finished = true; + p = ""; } } catch (IOException e) { @NonNull Object fromIOException = o; + @NonNull Object pFromIOException = p; } } catch (RuntimeException e) { // :: error: (assignment) @NonNull Object fromRuntimeException = o; + @NonNull Object pFromRuntimeException = p; } } catch (Error e) { // :: error: (assignment) @NonNull Object fromError = o; + @NonNull Object pFromError = p; } } } diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 9586019e7479..5ee7d5d3f3b7 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -1222,9 +1222,12 @@ \subsubsection{Handling \code{finally} blocks} behavior by adding a jump to a duplicate of the finally block before the jump to the original target of the control flow statement. -Likewise, an exception that the \code{try} block or a \code{catch} block -throws causes execution of the \code{finally} block, which then rethrows the -exception if the \code{finally} block completes normally. (If the +Likewise, an exception that propagates out of the \code{try} block (because +no \code{catch} block catches it) or out of a \code{catch} block causes +execution of the \code{finally} block, which then rethrows the exception if +the \code{finally} block completes normally. (An exception that a +\code{catch} block catches and does not rethrow is not pending when the +\code{finally} block executes, so it is not rethrown.) (If the \code{finally} block completes abruptly, for example by a \code{return} or \code{throw}, then that replaces the pending exception, which is not rethrown.) The Dataflow Framework models this behavior with further @@ -1236,11 +1239,13 @@ \subsubsection{Handling \code{finally} blocks} never meet. However, nested \code{finally} blocks multiply the duplicates, so their number can grow exponentially with the nesting depth of \code{finally} blocks in \code{finally} blocks. To bound this growth, the -Dataflow Framework bounds the number of nodes of the exceptional duplicates -beyond the first for each \code{finally} block. -Once the bound is reached, the exception types that do not yet have a +Dataflow Framework counts the nodes of the exceptional duplicates beyond +the first for each \code{finally} block. +Once the count reaches a threshold, the exception types that do not yet have a duplicate share one duplicate, even if they would be rethrown to different -places. In that case, the analysis might merge the stores of paths that never +places. (The threshold is not a strict cap on the number of nodes: the +count is checked before each duplicate is made, so a duplicate begun +below the threshold can take the count above it.) In that case, the analysis might merge the stores of paths that never meet, which can lead to false positive warnings. diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index f77498238e26..66249e882e44 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -293,9 +293,10 @@ public class CFGTranslationPhaseOne extends TreeScanner { Collections.newSetFromMap(new IdentityHashMap<>()); /** - * The maximum number of nodes in extra exceptional copies of finally blocks. Once the extra - * copies contain this many nodes, new exception types that reach a finally block share one - * exceptional copy of that finally block. + * The threshold on the number of nodes in extra exceptional copies of finally blocks. Once the + * extra copies contain this many nodes, new exception types that reach a finally block share one + * exceptional copy of that finally block. This is not a strict maximum: the count is checked + * before each copy is made, so a copy begun below the threshold can take the count above it. * *

An exceptional copy of a finally block is a translation of the finally block that runs when * an exception reaches the finally block, and that rethrows the exception after the finally block From 198ae8ef5bbe7288714b8eaceea01f7f538c9ca8 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 09:51:05 -0800 Subject: [PATCH 77/98] Test the sharing of an exceptional finally copy in the CFG; clarify which exceptions a finally block rethrows CFGConstruction checks that the exceptional copies of a finally block rethrow each exception type to its own catch block, before and after the budget for extra copies is used up. FinallyCopyBudget also checks that each catch block is reachable. The Dataflow Manual says that a finally block rethrows only a pending exception, and only if it completes normally, and that the budget is a threshold rather than a strict cap. --- checker/tests/nullness/FinallyCopyBudget.java | 23 +++- dataflow/manual/content.tex | 43 +++++--- .../cfg/builder/CFGTranslationPhaseOne.java | 12 ++- .../java/cfgconstruction/CFGConstruction.java | 94 ++++++++++++++++ dataflow/tests/cfgconstruction/Test.java | 101 ++++++++++++++++++ 5 files changed, 247 insertions(+), 26 deletions(-) diff --git a/checker/tests/nullness/FinallyCopyBudget.java b/checker/tests/nullness/FinallyCopyBudget.java index f9a12dc1b7da..ef8115be9339 100644 --- a/checker/tests/nullness/FinallyCopyBudget.java +++ b/checker/tests/nullness/FinallyCopyBudget.java @@ -3,7 +3,9 @@ // CFGTranslationPhaseOne.EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET. The exceptions that reach such a // finally block share one exceptional copy of it, which must rethrow each of them to the place // that it goes: here, a different catch block for each of IOException, RuntimeException, and -// Error. +// Error. This test checks that each catch block is reachable and that the exceptional copy is +// shared; method finallyCopyAfterBudgetIsUsedUp in dataflow/tests/cfgconstruction/Test.java checks +// the sharing in the CFG itself. // // The nested finally blocks at the beginning of afterBudgetIsUsedUp() use up the budget. If they // do not, the last finally block gets a separate copy for IOException, and the expected error in @@ -80,8 +82,13 @@ void afterBudgetIsUsedUp() { // might be null in each catch block, even the one for IOException. The finally block and the // catch blocks contain no method calls, so mightThrow() and log() are the only sources of the // exceptions that the catch blocks catch. + // + // The finally block sets p to a non-null value, so p is non-null in each catch block. This + // checks that the copy rethrows each exception to its catch block: if a catch block were + // unreachable, p would have its declared type, @Nullable, there, and the assignment of p would + // be an error. (The assignment of o would be an error in either case.) @Nullable Object o = ""; - boolean finished = false; + @Nullable Object p = null; try { try { try { @@ -91,19 +98,22 @@ void afterBudgetIsUsedUp() { log(); o = ""; } finally { - finished = true; + p = ""; } } catch (IOException e) { // :: error: (assignment) @NonNull Object fromIOException = o; + @NonNull Object pFromIOException = p; } } catch (RuntimeException e) { // :: error: (assignment) @NonNull Object fromRuntimeException = o; + @NonNull Object pFromRuntimeException = p; } } catch (Error e) { // :: error: (assignment) @NonNull Object fromError = o; + @NonNull Object pFromError = p; } } @@ -111,7 +121,7 @@ void beforeBudgetIsUsedUp() { // The same code as at the end of afterBudgetIsUsedUp(), but no earlier finally block uses up // the budget. So IOException has its own copy of the finally block, in which o is non-null. @Nullable Object o = ""; - boolean finished = false; + @Nullable Object p = null; try { try { try { @@ -121,18 +131,21 @@ void beforeBudgetIsUsedUp() { log(); o = ""; } finally { - finished = true; + p = ""; } } catch (IOException e) { @NonNull Object fromIOException = o; + @NonNull Object pFromIOException = p; } } catch (RuntimeException e) { // :: error: (assignment) @NonNull Object fromRuntimeException = o; + @NonNull Object pFromRuntimeException = p; } } catch (Error e) { // :: error: (assignment) @NonNull Object fromError = o; + @NonNull Object pFromError = p; } } } diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 5c8d9128d453..0ba39d04e913 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -949,6 +949,7 @@ \subsection{Formal Definition of the Control-Flow Graph} \code{NullChkNode} & \code{NullPointerException} \\ \code{ClassNameNode} & \code{ClassCircularityError}, \code{ClassFormatError}, \\ & \code{NoClassDefFoundError}, \code{OutOfMemoryError} \\ + \code{MarkerNode} & Types rethrown at the end of a \code{finally} block \\ \hline \end{tabular} @@ -1222,22 +1223,32 @@ \subsubsection{Handling \code{finally} blocks} behavior by adding a jump to a duplicate of the finally block before the jump to the original target of the control flow statement. -Likewise, an exception that the \code{try} block or a \code{catch} block -throws causes execution of the \code{finally} block, which then rethrows the -exception. The Dataflow Framework models this behavior with further -duplicates of the \code{finally} block, each of which ends by rethrowing the -exception. Exception types that would be rethrown to the same places (the -same \code{catch} blocks, or the exit of the method) share a duplicate. -Exception types that would be rethrown to different places get different -duplicates, so that the analysis does not merge the stores of paths that -never meet. However, nested \code{finally} blocks multiply the duplicates, -so their number can grow exponentially with the nesting depth of -\code{finally} blocks in \code{finally} blocks. To bound this growth, the -Dataflow Framework bounds the number of nodes of the exceptional duplicates -beyond the first for each \code{finally} block. -Once the bound is reached, the exception types that do not yet have a -duplicate share one duplicate, even if they would be rethrown to different -places. In that case, the analysis might merge the stores of paths that never +Likewise, an exception that escapes the \code{try} block (because no +\code{catch} block handles it) or that escapes a \code{catch} block causes +execution of the \code{finally} block. If the \code{finally} block +completes normally, the exception is then rethrown; if the \code{finally} +block completes abruptly, for example by a \code{return} or by throwing +another exception, that replaces the pending exception, which is not +rethrown. (An exception that a \code{catch} block handles and does not +rethrow is not pending when the \code{finally} block executes, so the +\code{finally} block runs but does not rethrow that exception.) The +Dataflow Framework models this behavior with further duplicates of the +\code{finally} block, each of which ends, if the \code{finally} block +completes normally, by rethrowing the exception. Exception types that +would be rethrown to the same places (the same \code{catch} blocks, or the +exit of the method) share a duplicate. Exception types that would be +rethrown to different places get different duplicates, so that the analysis +does not merge the stores of paths that never meet. However, nested +\code{finally} blocks multiply the duplicates, so their number can grow +exponentially with the nesting depth of \code{finally} blocks in +\code{finally} blocks. To bound this growth, the Dataflow Framework counts +the nodes of the exceptional duplicates beyond the first for each +\code{finally} block. Once the count reaches a threshold, the exception +types that do not yet have a duplicate share one duplicate, even if they +would be rethrown to different places. (The threshold is not a strict cap +on the number of nodes: the count is checked before each duplicate is +made, so a duplicate begun below the threshold can take the count above +it.) In that case, the analysis might merge the stores of paths that never meet, which can lead to false positive warnings. diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index bfa8680be9d6..bb179d7e3fc0 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -287,17 +287,19 @@ public class CFGTranslationPhaseOne extends TreeScanner { private SwitchBuilder switchBuilder; /** - * The maximum number of nodes in extra exceptional copies of finally blocks. Once the extra - * copies contain this many nodes, new exception types that reach a finally block share one - * exceptional copy of that finally block. + * The threshold on the number of nodes in extra exceptional copies of finally blocks. Once the + * extra copies contain this many nodes, new exception types that reach a finally block share one + * exceptional copy of that finally block. This is not a strict maximum: the count is checked + * before each copy is made, so a copy begun below the threshold can take the count above it. * *

An exceptional copy of a finally block is a translation of the finally block that runs when * an exception reaches the finally block, and that rethrows the exception after the finally block * completes normally. An extra copy is one other than the first exceptional copy of a given * finally block. See {@link #handleFinally}. * - *

The test {@code checker/tests/nullness/FinallyCopyBudget.java} uses up this budget, and it - * fails if it does not use up the budget. + *

The test {@code checker/tests/nullness/FinallyCopyBudget.java} and method {@code + * finallyCopyAfterBudgetIsUsedUp} in {@code dataflow/tests/cfgconstruction/Test.java} use up this + * budget, and they fail if they do not use it up. */ private static final int EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET = 10_000; diff --git a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java index cb697d515269..f0e6ee860e2c 100644 --- a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java +++ b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java @@ -1,6 +1,16 @@ package cfgconstruction; +import com.sun.source.tree.TryTree; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.lang.model.type.TypeMirror; import org.checkerframework.dataflow.cfg.ControlFlowGraph; +import org.checkerframework.dataflow.cfg.block.Block; +import org.checkerframework.dataflow.cfg.block.ExceptionBlock; +import org.checkerframework.dataflow.cfg.node.MarkerNode; import org.checkerframework.dataflow.cfg.visualize.CFGVisualizeLauncher; public class CFGConstruction { @@ -32,5 +42,89 @@ public static void main(String[] args) { if (cfg.getDeclaredClasses().size() != 1) { throw new Error("Expected 1 declared class, found " + cfg.getDeclaredClasses()); } + + // Before the budget for extra exceptional copies of finally blocks is used up, each exception + // type gets its own copy, because each goes to a different catch block. + cfg = + CFGVisualizeLauncher.generateMethodCFG( + inputFile, "finallyCopiesBeforeBudgetIsUsedUp", clazz, /* analysis= */ null); + cfg.checkInvariants(); + List copyEnds = exceptionalCopyEnds(cfg); + if (copyEnds.size() != 3) { + throw new Error("Expected 3 exceptional copies, found " + copyEnds.size()); + } + checkRethrowsToDistinctHandlers(copyEnds); + + // After the budget is used up, the exception types share one copy, which rethrows each of them + // to its own catch block. + cfg = + CFGVisualizeLauncher.generateMethodCFG( + inputFile, "finallyCopyAfterBudgetIsUsedUp", clazz, /* analysis= */ null); + cfg.checkInvariants(); + copyEnds = exceptionalCopyEnds(cfg); + if (copyEnds.size() != 1) { + throw new Error("Expected 1 shared exceptional copy, found " + copyEnds.size()); + } + checkRethrowsToDistinctHandlers(copyEnds); + } + + /** + * Returns the blocks that end the exceptional copies of the finally block that assigns {@code + * finished}. Each such block rethrows the exceptions that its copy handles. + * + * @param cfg a control flow graph + * @return the blocks whose node is the marker at the end of an exceptional copy of the finally + * block that assigns {@code finished} + */ + private static List exceptionalCopyEnds(ControlFlowGraph cfg) { + List result = new ArrayList<>(); + for (Block block : cfg.getAllBlocks()) { + if (block instanceof ExceptionBlock exceptionBlock + && exceptionBlock.getNode() instanceof MarkerNode marker + && marker.getMessage().startsWith("end of finally block for ") + && marker.getTree() instanceof TryTree tryTree + && tryTree.getFinallyBlock() != null + && tryTree.getFinallyBlock().toString().contains("finished = true")) { + result.add(exceptionBlock); + } + } + return result; + } + + /** + * Checks that the given blocks together rethrow exactly IOException, RuntimeException, and Error, + * each to a different catch block. + * + * @param copyEnds the blocks that end the exceptional copies of a finally block + */ + private static void checkRethrowsToDistinctHandlers(List copyEnds) { + Set typeNames = new HashSet<>(); + Set handlers = new HashSet<>(); + int numEdges = 0; + for (ExceptionBlock copyEnd : copyEnds) { + for (Map.Entry> entry : + copyEnd.getExceptionalSuccessors().entrySet()) { + typeNames.add(entry.getKey().toString()); + if (entry.getValue().size() != 1) { + throw new Error( + "Expected 1 successor for " + entry.getKey() + ", found " + entry.getValue()); + } + handlers.addAll(entry.getValue()); + numEdges++; + } + } + Set expectedTypeNames = + Set.of("java.io.IOException", "java.lang.RuntimeException", "java.lang.Error"); + if (!typeNames.equals(expectedTypeNames) || numEdges != 3) { + throw new Error("Expected rethrows of " + expectedTypeNames + ", found " + typeNames); + } + if (handlers.size() != 3) { + throw new Error("Expected rethrows to 3 different catch blocks, found " + handlers); + } + for (Block handler : handlers) { + if (handler.getType() == Block.BlockType.SPECIAL_BLOCK) { + throw new Error("Expected rethrows to catch blocks, found " + handler); + } + } } } diff --git a/dataflow/tests/cfgconstruction/Test.java b/dataflow/tests/cfgconstruction/Test.java index 361af2939fee..0f1547e3fc15 100644 --- a/dataflow/tests/cfgconstruction/Test.java +++ b/dataflow/tests/cfgconstruction/Test.java @@ -1,3 +1,5 @@ +import java.io.IOException; + public class Test { public void manyNestedTryFinallyBlocks() { @@ -37,4 +39,103 @@ class Local {} } return null; } + + void mightThrow() throws IOException {} + + void log() {} + + // The finally block that assigns `finished` has one exceptional copy, which rethrows + // IOException, RuntimeException, and Error to three different catch blocks. The nested finally + // blocks before it use up CFGTranslationPhaseOne.EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET. If the + // budget is increased, deepen their nesting so that they still use it up. This method is like + // the method in checker/tests/nullness/FinallyCopyBudget.java. + public void finallyCopyAfterBudgetIsUsedUp() { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + try { + try { + mightThrow(); + } finally { + log(); + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + } + } catch (IOException e) { + } + + boolean finished = false; + try { + try { + try { + try { + mightThrow(); + } finally { + finished = true; + } + } catch (IOException e) { + } + } catch (RuntimeException e) { + } + } catch (Error e) { + } + } + + // This method is like the end of the previous one. Because the budget is not used up, the + // finally block that assigns `finished` has three exceptional copies, one for each of + // IOException, RuntimeException, and Error. + public void finallyCopiesBeforeBudgetIsUsedUp() { + boolean finished = false; + try { + try { + try { + try { + mightThrow(); + } finally { + finished = true; + } + } catch (IOException e) { + } + } catch (RuntimeException e) { + } + } catch (Error e) { + } + } } From 96d7d56a080c6dde82c2351196ffc0d3b46b39e4 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 09:57:55 -0800 Subject: [PATCH 78/98] Throw IllegalArgumentException from addSuppressed only if close might throw the primary exception The synthetic addSuppressed call of a try-with-resources statement throws IllegalArgumentException only if close() might throw the primary exception itself, that is, only if a type of the primary exception overlaps a type that close() might throw. The types that close() might throw come from its throws clause as a member of the resource's type, so close() of a GenericResource throws OtherException, not every Exception. Primary exception types that close() might throw and those that it cannot throw get different copies of the synthetic finally block, because only the former copies have the IllegalArgumentException edge. --- .../TryWithResourcesSelfSuppression.java | 133 +++++++++++++++++- dataflow/manual/content.tex | 4 +- .../cfg/builder/CFGTranslationPhaseOne.java | 118 ++++++++++++++-- 3 files changed, 236 insertions(+), 19 deletions(-) diff --git a/checker/tests/nullness/TryWithResourcesSelfSuppression.java b/checker/tests/nullness/TryWithResourcesSelfSuppression.java index 87809b38ac6b..95cf67bc12b4 100644 --- a/checker/tests/nullness/TryWithResourcesSelfSuppression.java +++ b/checker/tests/nullness/TryWithResourcesSelfSuppression.java @@ -2,7 +2,8 @@ // A try-with-resources statement suppresses an exception that close() throws by calling // addSuppressed() on the primary exception. If close() throws the primary exception itself, then -// addSuppressed() throws an IllegalArgumentException, which replaces the primary exception. +// addSuppressed() throws an IllegalArgumentException, which replaces the primary exception. That +// is possible only if close() might throw an exception that has a type of the primary exception. public class TryWithResourcesSelfSuppression { static class MyException extends Exception {} @@ -12,7 +13,19 @@ interface Resource extends AutoCloseable { void close(); } - void selfSuppression(Resource r, MyException ex) throws MyException { + interface ResourceThrowingMyException extends AutoCloseable { + @Override + void close() throws MyException; + } + + static class OtherException extends Exception {} + + interface GenericResource extends AutoCloseable { + @Override + void close() throws E; + } + + void selfSuppression(Resource r, NullPointerException ex) { @Nullable Object o = ""; try { try (r) { @@ -20,9 +33,123 @@ void selfSuppression(Resource r, MyException ex) throws MyException { throw ex; } } catch (IllegalArgumentException e) { - // The handler is reachable only through the addSuppressed() call. + // The handler is reachable only through the addSuppressed() call. The primary exception is + // a NullPointerException, which close() might throw. + // :: error: (dereference.of.nullable) + o.toString(); + } + } + + // In the next two methods, the primary exception is always a MyException: the inner catch + // clause catches every unchecked exception that the try block throws. The inner catch clause + // makes o non-null before the return statement, so o is non-null on the path on which the + // normal-path close() throws an IllegalArgumentException. + + void selfSuppressionOfCheckedException(ResourceThrowingMyException r, MyException ex) + throws MyException { + @Nullable Object o = ""; + try { + try (r) { + try { + o = null; + throw ex; + } catch (RuntimeException | Error e) { + o = ""; + return; + } + } + } catch (IllegalArgumentException e) { + // close() might throw the primary exception itself, so the handler is reachable through the + // addSuppressed() call. + // :: error: (dereference.of.nullable) + o.toString(); + } + } + + void noSelfSuppression(Resource r, MyException ex) throws MyException { + @Nullable Object o = ""; + try { + try (r) { + try { + o = null; + throw ex; + } catch (RuntimeException | Error e) { + o = ""; + return; + } + } + } catch (IllegalArgumentException e) { + // close() cannot throw a MyException, so it cannot throw the primary exception, and the + // addSuppressed() call does not throw. + o.toString(); + } + } + + // For a GenericResource, close() throws OtherException, not every Exception, so + // it cannot throw the primary exception, a MyException. + void noSelfSuppressionForGenericResource(GenericResource r, MyException ex) + throws MyException, OtherException { + @Nullable Object o = ""; + try { + try (r) { + try { + o = null; + throw ex; + } catch (RuntimeException | Error e) { + o = ""; + return; + } + } + } catch (IllegalArgumentException e) { + o.toString(); + } + } + + void selfSuppressionForGenericResource(GenericResource r, MyException ex) + throws MyException { + @Nullable Object o = ""; + try { + try (r) { + try { + o = null; + throw ex; + } catch (RuntimeException | Error e) { + o = ""; + return; + } + } + } catch (IllegalArgumentException e) { // :: error: (dereference.of.nullable) o.toString(); } } + + // A MyException and an OtherException reach the same catch clause, but only a MyException can be + // the exception that close() throws. So they get different copies of the synthetic finally + // block, and only the copy for MyException, in which o is non-null, reaches the + // IllegalArgumentException handler through the addSuppressed() call. + void selfSuppressionOnlyForTypesThatCloseThrows( + ResourceThrowingMyException r, MyException ex, OtherException other, boolean b) { + @Nullable Object o = ""; + try { + try { + try (r) { + try { + if (b) { + throw ex; + } + o = null; + throw other; + } catch (RuntimeException | Error e) { + o = ""; + return; + } + } + } catch (MyException | OtherException e) { + o = ""; + } + } catch (IllegalArgumentException e) { + o.toString(); + } + } } diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 0ba39d04e913..39eafaf2d0b3 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -949,7 +949,9 @@ \subsection{Formal Definition of the Control-Flow Graph} \code{NullChkNode} & \code{NullPointerException} \\ \code{ClassNameNode} & \code{ClassCircularityError}, \code{ClassFormatError}, \\ & \code{NoClassDefFoundError}, \code{OutOfMemoryError} \\ - \code{MarkerNode} & Types rethrown at the end of a \code{finally} block \\ + \code{MarkerNode} & Types rethrown at the end of a \code{finally} block; \\ + & \code{IllegalArgumentException} (synthetic \code{addSuppressed} in \\ + & try-with-resources) \\ \hline \end{tabular} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index a19c87ff5b1b..b660309419d0 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -74,6 +74,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; +import java.util.function.Predicate; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; @@ -2692,6 +2693,7 @@ public Node visitTry(TryTree tree, Void p) { doneLabel, finallyLabel, exceptionalFinallyFrame, + type -> false, () -> scan(finallyBlock, p), primaryExceptionTypes -> scan(finallyBlock, p), oldReturnTargetLC, @@ -2785,15 +2787,20 @@ private void handleTryResourcesAndBlock(TryTree tryTree, Void p, List closeThrownTypes = closeThrownTypes(resourceDeclarationTree); handleFinally( resourceDeclarationTree, doneLabel, finallyLabel, exceptionalFinallyFrame, + type -> mayThrowSameException(Collections.singleton(type), closeThrownTypes), () -> addCloseCallForResource(resourceDeclarationTree, p), primaryExceptionTypes -> - addSuppressingCloseCallForResource(resourceDeclarationTree, primaryExceptionTypes, p), + addSuppressingCloseCallForResource( + resourceDeclarationTree, primaryExceptionTypes, closeThrownTypes, p), oldReturnTargetLC, oldBreakTargetLC, oldBreakLabels, @@ -2906,7 +2913,11 @@ private void addCloseCallForResource( * the primary exception (JLS 14.20.3.1). So every exceptional successor of the {@code close} call * is a node that models the call to {@code addSuppressed}. That node may throw {@code * IllegalArgumentException}, which {@code addSuppressed} throws if {@code close} threw the - * primary exception itself; otherwise it reaches the rethrow of the primary exception. + * primary exception itself; otherwise it reaches the rethrow of the primary exception. The node + * throws {@code IllegalArgumentException} only if some type of the primary exception overlaps + * some type of the exceptions that {@code close} might throw (the types in its {@code throws} + * clause and the unchecked exception types); the extra types that label edges of the call do not + * count. * *

The types of the primary exception label exceptional edges of the call, which lead to the * rethrow, in addition to the types of the exceptions that {@code close} might throw. So an @@ -2930,10 +2941,15 @@ private void addCloseCallForResource( * @param resourceDeclarationTree the resource declaration, or the variable or field that is the * resource * @param primaryExceptionTypes the types of the primary exception + * @param closeThrownTypes the types in the {@code throws} clause of {@code close}, as a member of + * the type of the resource (see {@link #closeThrownTypes}) * @param p the value to pass to calls to {@code scan} */ private void addSuppressingCloseCallForResource( - Tree resourceDeclarationTree, Set primaryExceptionTypes, Void p) { + Tree resourceDeclarationTree, + Set primaryExceptionTypes, + List closeThrownTypes, + Void p) { Label suppressedLabel = new Label(); tryStack.pushFrame( new TryCatchFrame( @@ -2946,18 +2962,79 @@ private void addSuppressingCloseCallForResource( extendWithExtendedNode(new UnconditionalJump(afterSuppressionLabel)); // The catch block calls addSuppressed on the primary exception, which throws - // IllegalArgumentException if close threw the primary exception itself. + // IllegalArgumentException if close threw the primary exception itself. That is possible + // only if the primary exception has a type that close might throw. addLabelForNextNode(suppressedLabel); - extendWithNodeWithException( + MarkerNode addSuppressedNode = new MarkerNode( resourceDeclarationTree, "addSuppressed for resource #" + TreeUtils.treeUids.get(resourceDeclarationTree), - env.getTypeUtils()), - illegalArgumentExceptionType); + env.getTypeUtils()); + if (mayThrowSameException(primaryExceptionTypes, closeThrownTypes)) { + extendWithNodeWithException(addSuppressedNode, illegalArgumentExceptionType); + } else { + extendWithNode(addSuppressedNode); + } addLabelForNextNode(afterSuppressionLabel); } + /** + * Returns the types in the {@code throws} clause of the {@code close} method of a resource, as a + * member of the type of the resource. For example, if the resource has type {@code + * R} and {@code R} declares {@code void close() throws E}, the + * result is {@code [IOException]}, not {@code [E]}. + * + * @param resourceDeclarationTree the resource declaration, or the variable or field that is the + * resource + * @return the types in the {@code throws} clause of {@code close}, as a member of the type of the + * resource + */ + private List closeThrownTypes(Tree resourceDeclarationTree) { + TypeMirror resourceType = TreeUtils.typeOf(resourceDeclarationTree); + ExecutableElement closeMethod = ElementUtils.resolveNoArgumentCall(resourceType, "close", env); + if (closeMethod == null) { + throw new BugInCF("no close method for %s of type %s", resourceDeclarationTree, resourceType); + } + if (TypesUtils.upperBound(resourceType) instanceof DeclaredType declaredType) { + try { + return ((ExecutableType) types.asMemberOf(declaredType, closeMethod)).getThrownTypes(); + } catch (IllegalArgumentException e) { + // The declared type does not have `closeMethod` as a member; fall through. + } + } + return closeMethod.getThrownTypes(); + } + + /** + * Returns true if a method whose {@code throws} clause is {@code thrownTypes} might throw an + * exception that has one of the given types. That is, returns true if one of the given types is a + * subtype or supertype of a type in {@code thrownTypes} or of an unchecked exception type. + * + * @param exceptionTypes the types of an exception + * @param thrownTypes the types in the {@code throws} clause of a method + * @return true if the method might throw an exception that has one of {@code exceptionTypes} + */ + private boolean mayThrowSameException( + Set exceptionTypes, List thrownTypes) { + List mayThrow = + new ArrayList<>(thrownTypes.size() + uncheckedExceptionTypes.size()); + mayThrow.addAll(thrownTypes); + mayThrow.addAll(uncheckedExceptionTypes); + for (TypeMirror exceptionType : exceptionTypes) { + TypeMirror exceptionErased = types.erasure(exceptionType); + for (TypeMirror thrownType : mayThrow) { + // Erasure replaces a type variable, such as one in a throws clause, by its upper bound. + TypeMirror thrownErased = types.erasure(thrownType); + if (types.isSubtype(exceptionErased, thrownErased) + || types.isSubtype(thrownErased, exceptionErased)) { + return true; + } + } + } + return false; + } + /** * Shared logic for CFG generation for a finally block. The block might correspond to a {@link * TryTree} originally in the source code, or it might be a synthetic finally block used to model @@ -2970,6 +3047,9 @@ private void addSuppressingCloseCallForResource( * @param exceptionalFinallyFrame the frame that the exceptions of the try block and of the catch * blocks reach; its labels are the entries of the copies of the finally block for when the * try block or a catch block throws an exception + * @param separateCopies two types of exceptions on which this predicate differs never share a + * copy of the finally block, unless the budget for copies is used up; use it when the copy's + * edges depend on the types that it rethrows * @param finallyBlockCFGGenerator generates CFG nodes and edges for the finally block, for each * path except the ones on which an exception reaches the finally block * @param exceptionalFinallyBlockCFGGenerator generates CFG nodes and edges for the finally block, @@ -2991,6 +3071,7 @@ private void handleFinally( Label doneLabel, Label finallyLabel, TryFinallyFrame exceptionalFinallyFrame, + Predicate separateCopies, Runnable finallyBlockCFGGenerator, Consumer> exceptionalFinallyBlockCFGGenerator, LabelCell oldReturnTargetLC, @@ -3041,7 +3122,11 @@ private void handleFinally( // finally blocks. To bound that growth, once the copies beyond the first copy for each finally // block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that do not // yet have a copy share a single copy, which rethrows each of their exceptions. - List groups = new ArrayList<>(rethrowGroups(exceptionalFinallyFrame)); + // + // Two types also get different copies if `separateCopies` differs on them, because then the + // copies themselves have different edges. + List groups = + new ArrayList<>(rethrowGroups(exceptionalFinallyFrame, separateCopies)); for (int i = 0; i < groups.size(); i++) { // Making the previous copies, and the copies of finally blocks nested in them, might have @@ -3215,19 +3300,22 @@ private void handleFinally( /** * Returns the types of the exceptions that reach the given frame, grouped by where a copy of the * finally block rethrows them. Two types are in the same group if and only if {@link - * TryStack#possibleLabelsPastFinally} returns the same set of labels for each of them. + * TryStack#possibleLabelsPastFinally} returns the same set of labels for each of them and {@code + * separateCopies} returns the same value for each of them. * * @param frame a frame for a finally block, which the CFG builder has popped from the try stack + * @param separateCopies two types on which this predicate differs are in different groups * @return the groups, in a deterministic order; the entry label of each type is its label in * {@code frame}. Empty if no exception reaches {@code frame}. */ - private Collection rethrowGroups(TryFinallyFrame frame) { - Map, RethrowGroup> groups = new LinkedHashMap<>(); + private Collection rethrowGroups( + TryFinallyFrame frame, Predicate separateCopies) { + Map, RethrowGroup> groups = new LinkedHashMap<>(); for (Map.Entry entry : frame.getExceptionLabels().entrySet()) { TypeMirror type = entry.getKey(); - groups - .computeIfAbsent(tryStack.possibleLabelsPastFinally(type), labels -> new RethrowGroup()) - .add(type, entry.getValue()); + List key = + List.of(tryStack.possibleLabelsPastFinally(type), separateCopies.test(type)); + groups.computeIfAbsent(key, k -> new RethrowGroup()).add(type, entry.getValue()); } return groups.values(); } From c977c711ce2ca7763f823fbd37b8439444987720 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 10:13:25 -0800 Subject: [PATCH 79/98] Exclude a supertype's private method from the implicit calls of try-with-resources and enhanced for noArgMethods now uses Elements.getAllMembers, which omits a method that the type does not inherit, such as a private close() of a superclass. --- .../checker/nullness/NullnessTransfer.java | 19 ++++++++------ .../ReceiverReassignedByImplicitCall.java | 26 +++++++++++++++++++ 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 089466d54c22..235e5ed53520 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -26,6 +26,7 @@ import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import org.checkerframework.checker.initialization.InitializationTransfer; import org.checkerframework.checker.nullness.qual.NonNull; @@ -56,7 +57,6 @@ import org.checkerframework.javacutil.AnnotationBuilder; import org.checkerframework.javacutil.AnnotationMirrorSet; import org.checkerframework.javacutil.AnnotationUtils; -import org.checkerframework.javacutil.ElementUtils; import org.checkerframework.javacutil.TreeUtils; import org.checkerframework.javacutil.TypeSystemError; import org.checkerframework.javacutil.TypesUtils; @@ -831,12 +831,12 @@ private boolean noArgMethodMayHaveSideEffect( } /* - * Returns the no-argument methods with the given name that are members of the erasure - * of the given type, omitting each method that another of them overrides. (The - * checker requires an overriding method to be at least as pure as the method it - * overrides.) Returns more than one method if the type inherits several of them, which - * is conservative. Returns an empty list if the erasure has no type element, as for an - * array type. + * Returns the no-argument methods with the given name that are members (declared or + * inherited) of the erasure of the given type, omitting each method that another of + * them overrides. (The checker requires an overriding method to be at least as pure as + * the method it overrides.) Returns more than one method if the type inherits several + * of them, which is conservative. Returns an empty list if the erasure has no type + * element, as for an array type. * * @param type a type * @param name a method name @@ -849,7 +849,10 @@ private List noArgMethods(TypeMirror type, String name) { } Elements elements = nullnessTypeFactory.getElementUtils(); List candidates = new ArrayList<>(); - for (ExecutableElement m : ElementUtils.getAllMethodsIn(typeElement, elements)) { + // getAllMembers omits a method that the type does not inherit, such as a private + // method of a supertype. + for (ExecutableElement m : + ElementFilter.methodsIn(elements.getAllMembers(typeElement))) { if (m.getSimpleName().contentEquals(name) && m.getParameters().isEmpty()) { candidates.add(m); } diff --git a/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java index ee11a42c1224..69bcc4c1e442 100644 --- a/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java +++ b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java @@ -68,6 +68,32 @@ void resourceCloseIsPure(int tag) { f.toString(); } + class ResourceBase { + // Not inherited by PureResourceWithPrivateClose, so try-with-resources does not invoke it. + private void close() { + f = null; + } + } + + class PureResourceWithPrivateClose extends ResourceBase implements AutoCloseable { + @Override + @SideEffectFree + public void close() {} + } + + void resourceCloseIsPureDespitePrivateSuperclassClose(int tag) { + PureResourceWithPrivateClose resource = new PureResourceWithPrivateClose(); + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + try (resource) {} + yield 0; + } + }); + f.toString(); + } + // A try statement without resources invokes no method. void tryWithoutResources(int tag) { // :: error: (dereference.of.nullable) From 7b24676a46e29288cb01e431b74a931e134d666f Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 11:58:14 -0800 Subject: [PATCH 80/98] Dataflow Manual: the finally-copy budget counts nodes across all finally blocks in a method --- dataflow/manual/content.tex | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 0ba39d04e913..fa768403cf10 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -1242,8 +1242,9 @@ \subsubsection{Handling \code{finally} blocks} \code{finally} blocks multiply the duplicates, so their number can grow exponentially with the nesting depth of \code{finally} blocks in \code{finally} blocks. To bound this growth, the Dataflow Framework counts -the nodes of the exceptional duplicates beyond the first for each -\code{finally} block. Once the count reaches a threshold, the exception +the nodes, across all \code{finally} blocks in a method, of the exceptional +duplicates beyond the first for each \code{finally} block. Once the count +reaches a threshold, the exception types that do not yet have a duplicate share one duplicate, even if they would be rethrown to different places. (The threshold is not a strict cap on the number of nodes: the count is checked before each duplicate is From 4d246007118e7cd7d4177eca02a451915b314a01 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 12:57:44 -0800 Subject: [PATCH 81/98] Resource Leak Checker manual: an exception from close() in the catch block replaces the rethrown one --- docs/manual/resource-leak-checker.tex | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/manual/resource-leak-checker.tex b/docs/manual/resource-leak-checker.tex index 7f584a3d6cdb..287e6b92ad17 100644 --- a/docs/manual/resource-leak-checker.tex +++ b/docs/manual/resource-leak-checker.tex @@ -637,6 +637,8 @@ Java permits \ in a method that is declared to throw only \, because the only checked exceptions that \ can hold are those that the \ block can throw. +If \ itself throws an exception, that exception propagates +instead of \, just as in the version that uses \. \sectionAndLabel{Errors about field initialization}{resource-leak-field-initialization} From 223de98fe52d3b3d6e38961c6540815dbae893e2 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 13:15:50 -0800 Subject: [PATCH 82/98] Paragraph break --- dataflow/manual/content.tex | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index fa768403cf10..4b190da54d43 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -1238,19 +1238,20 @@ \subsubsection{Handling \code{finally} blocks} would be rethrown to the same places (the same \code{catch} blocks, or the exit of the method) share a duplicate. Exception types that would be rethrown to different places get different duplicates, so that the analysis -does not merge the stores of paths that never meet. However, nested -\code{finally} blocks multiply the duplicates, so their number can grow -exponentially with the nesting depth of \code{finally} blocks in -\code{finally} blocks. To bound this growth, the Dataflow Framework counts -the nodes, across all \code{finally} blocks in a method, of the exceptional -duplicates beyond the first for each \code{finally} block. Once the count -reaches a threshold, the exception -types that do not yet have a duplicate share one duplicate, even if they -would be rethrown to different places. (The threshold is not a strict cap -on the number of nodes: the count is checked before each duplicate is -made, so a duplicate begun below the threshold can take the count above -it.) In that case, the analysis might merge the stores of paths that never -meet, which can lead to false positive warnings. +does not merge the stores of paths that never meet. + +However, nested \code{finally} blocks multiply the duplicates, so their +number can grow exponentially with the nesting depth of \code{finally} +blocks in \code{finally} blocks. To bound this growth, the Dataflow +Framework counts the nodes, across all \code{finally} blocks in a method, +of the exceptional duplicates beyond the first for each \code{finally} +block. Once the count reaches a threshold, the exception types that do not +yet have a duplicate share one duplicate, even if they would be rethrown to +different places. (The threshold is not a strict cap on the number of +nodes: the count is checked before each duplicate is made, so a duplicate +begun below the threshold can take the count above it.) In that case, the +analysis might merge the stores of paths that never meet, which can lead to +false positive warnings. \subsection{AST to CFG Translation} From 71d1c72fb987aafb90090c302ee99016d95d8dc9 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 13:18:04 -0800 Subject: [PATCH 83/98] Move the budget for exceptional copies of finally blocks to its own pull request The exceptional copies of a finally block still rethrow each exception type to the place that it goes, and types that go to the same places share a copy. --- checker/tests/nullness/FinallyCopyBudget.java | 151 ------------------ dataflow/manual/content.tex | 13 -- .../cfg/builder/CFGTranslationPhaseOne.java | 73 ++------- .../dataflow/cfg/builder/RethrowGroup.java | 16 -- .../java/cfgconstruction/CFGConstruction.java | 18 +-- dataflow/tests/cfgconstruction/Test.java | 84 +--------- 6 files changed, 18 insertions(+), 337 deletions(-) delete mode 100644 checker/tests/nullness/FinallyCopyBudget.java diff --git a/checker/tests/nullness/FinallyCopyBudget.java b/checker/tests/nullness/FinallyCopyBudget.java deleted file mode 100644 index ef8115be9339..000000000000 --- a/checker/tests/nullness/FinallyCopyBudget.java +++ /dev/null @@ -1,151 +0,0 @@ -// Tests the exceptional copy of a finally block that the CFG builder creates after the extra -// exceptional copies of earlier finally blocks in the same method have used up -// CFGTranslationPhaseOne.EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET. The exceptions that reach such a -// finally block share one exceptional copy of it, which must rethrow each of them to the place -// that it goes: here, a different catch block for each of IOException, RuntimeException, and -// Error. This test checks that each catch block is reachable and that the exceptional copy is -// shared; method finallyCopyAfterBudgetIsUsedUp in dataflow/tests/cfgconstruction/Test.java checks -// the sharing in the CFG itself. -// -// The nested finally blocks at the beginning of afterBudgetIsUsedUp() use up the budget. If they -// do not, the last finally block gets a separate copy for IOException, and the expected error in -// its catch block for IOException does not occur, so the test fails. In that case, deepen their -// nesting so that they use up the budget. - -import java.io.IOException; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; - -abstract class FinallyCopyBudget { - abstract void mightThrow() throws IOException; - - abstract void log(); - - void afterBudgetIsUsedUp() { - // These finally blocks use up the budget. Each of them has two exceptional copies: one - // rethrows IOException to the catch block, and the other rethrows RuntimeException and Error - // out of the method. Nesting makes the number of copies grow exponentially. - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - log(); - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - - // This finally block has one exceptional copy, which rethrows all three exceptions. An - // IOException comes only from mightThrow(), when o is non-null. A RuntimeException or an Error - // also comes from log(), when o is null. The copy merges the stores of all those paths, so o - // might be null in each catch block, even the one for IOException. The finally block and the - // catch blocks contain no method calls, so mightThrow() and log() are the only sources of the - // exceptions that the catch blocks catch. - // - // The finally block sets p to a non-null value, so p is non-null in each catch block. This - // checks that the copy rethrows each exception to its catch block: if a catch block were - // unreachable, p would have its declared type, @Nullable, there, and the assignment of p would - // be an error. (The assignment of o would be an error in either case.) - @Nullable Object o = ""; - @Nullable Object p = null; - try { - try { - try { - try { - mightThrow(); - o = null; - log(); - o = ""; - } finally { - p = ""; - } - } catch (IOException e) { - // :: error: (assignment) - @NonNull Object fromIOException = o; - @NonNull Object pFromIOException = p; - } - } catch (RuntimeException e) { - // :: error: (assignment) - @NonNull Object fromRuntimeException = o; - @NonNull Object pFromRuntimeException = p; - } - } catch (Error e) { - // :: error: (assignment) - @NonNull Object fromError = o; - @NonNull Object pFromError = p; - } - } - - void beforeBudgetIsUsedUp() { - // The same code as at the end of afterBudgetIsUsedUp(), but no earlier finally block uses up - // the budget. So IOException has its own copy of the finally block, in which o is non-null. - @Nullable Object o = ""; - @Nullable Object p = null; - try { - try { - try { - try { - mightThrow(); - o = null; - log(); - o = ""; - } finally { - p = ""; - } - } catch (IOException e) { - @NonNull Object fromIOException = o; - @NonNull Object pFromIOException = p; - } - } catch (RuntimeException e) { - // :: error: (assignment) - @NonNull Object fromRuntimeException = o; - @NonNull Object pFromRuntimeException = p; - } - } catch (Error e) { - // :: error: (assignment) - @NonNull Object fromError = o; - @NonNull Object pFromError = p; - } - } -} diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 4b190da54d43..ba9067a5f7b1 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -1240,19 +1240,6 @@ \subsubsection{Handling \code{finally} blocks} rethrown to different places get different duplicates, so that the analysis does not merge the stores of paths that never meet. -However, nested \code{finally} blocks multiply the duplicates, so their -number can grow exponentially with the nesting depth of \code{finally} -blocks in \code{finally} blocks. To bound this growth, the Dataflow -Framework counts the nodes, across all \code{finally} blocks in a method, -of the exceptional duplicates beyond the first for each \code{finally} -block. Once the count reaches a threshold, the exception types that do not -yet have a duplicate share one duplicate, even if they would be rethrown to -different places. (The threshold is not a strict cap on the number of -nodes: the count is checked before each duplicate is made, so a duplicate -begun below the threshold can take the count above it.) In that case, the -analysis might merge the stores of paths that never meet, which can lead to -false positive warnings. - \subsection{AST to CFG Translation} \label{sec:ast_to_cfg_translation} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index bb179d7e3fc0..269933fb021f 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -286,30 +286,6 @@ public class CFGTranslationPhaseOne extends TreeScanner { /** SwitchBuilder for the current switch. Used to match yield statements to enclosing switches. */ private SwitchBuilder switchBuilder; - /** - * The threshold on the number of nodes in extra exceptional copies of finally blocks. Once the - * extra copies contain this many nodes, new exception types that reach a finally block share one - * exceptional copy of that finally block. This is not a strict maximum: the count is checked - * before each copy is made, so a copy begun below the threshold can take the count above it. - * - *

An exceptional copy of a finally block is a translation of the finally block that runs when - * an exception reaches the finally block, and that rethrows the exception after the finally block - * completes normally. An extra copy is one other than the first exceptional copy of a given - * finally block. See {@link #handleFinally}. - * - *

The test {@code checker/tests/nullness/FinallyCopyBudget.java} and method {@code - * finallyCopyAfterBudgetIsUsedUp} in {@code dataflow/tests/cfgconstruction/Test.java} use up this - * budget, and they fail if they do not use it up. - */ - private static final int EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET = 10_000; - - /** - * The number of nodes in extra exceptional copies of finally blocks so far. A node is counted - * once for each extra copy that contains it, so a node in an extra copy that is nested within - * another extra copy is counted more than once. - */ - private int extraExceptionalFinallyNodes = 0; - /** * Maps from AST {@link Tree}s to sets of {@link Node}s. Every Tree that produces a value will * have at least one corresponding Node. Trees that undergo implicit conversions, such as boxing @@ -2929,38 +2905,17 @@ private void handleFinally( // jump to when they reach this finally block, and the copy rethrows the group's types after // this finally block completes normally. // - // For precision, until the EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET budget is used up, two types - // share a copy if and only if the copy rethrows them to the same places. The analysis merges - // the stores of the paths that reach a copy. Types that go to the same places lose little - // precision by sharing a copy, because the analysis merges their stores at those places anyway. - // Sharing a copy merges the stores before the finally block rather than after it, which loses - // precision only if a transfer function in the finally block yields more precise results on - // the separate stores than on their merge. Types that go to different places get different - // copies, so that the analysis does not merge stores of paths that never meet. For example, - // the Resource Leak Checker would otherwise report a leak when an exception thrown while a - // resource is open is caught by a catch block that closes the resource, and another exception, - // thrown after the resource is closed, propagates out of the method. - // - // The number of copies grows exponentially with the depth of the nesting of finally blocks in - // finally blocks. To bound that growth, once the copies beyond the first copy for each finally - // block have contributed EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET nodes, the groups that do not - // yet have a copy share a single copy, which rethrows each of their exceptions. - List groups = new ArrayList<>(rethrowGroups(exceptionalFinallyFrame)); - - for (int i = 0; i < groups.size(); i++) { - // Making the previous copies, and the copies of finally blocks nested in them, might have - // used up the budget. This merges groups, before finally blocks are created for them. - if (i < groups.size() - 1 - && extraExceptionalFinallyNodes >= EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET) { - List remainingGroups = groups.subList(i, groups.size()); - RethrowGroup sharedGroup = RethrowGroup.merge(remainingGroups); - remainingGroups.clear(); - groups.add(sharedGroup); - } - RethrowGroup group = groups.get(i); - boolean isExtraCopy = i > 0; - int sizeBeforeCopy = nodeList.size(); - + // For precision, two types share a copy if and only if the copy rethrows them to the same + // places. The analysis merges the stores of the paths that reach a copy. Types that go to the + // same places lose little precision by sharing a copy, because the analysis merges their stores + // at those places anyway. Sharing a copy merges the stores before the finally block rather + // than after it, which loses precision only if a transfer function in the finally block yields + // more precise results on the separate stores than on their merge. Types that go to different + // places get different copies, so that the analysis does not merge stores of paths that never + // meet. For example, the Resource Leak Checker would otherwise report a leak when an exception + // thrown while a resource is open is caught by a catch block that closes the resource, and + // another exception, thrown after the resource is closed, propagates out of the method. + for (RethrowGroup group : rethrowGroups(exceptionalFinallyFrame)) { for (Label label : group.entryLabels()) { addLabelForNextNode(label); } @@ -2988,12 +2943,6 @@ private void handleFinally( group.types()); throwing.setTerminatesExecution(true); - - if (isExtraCopy) { - // The inner `handleFinally` already counted the nodes of any extra copy nested in this - // one, so this counts them again, which is conservative. - extraExceptionalFinallyNodes += nodeList.size() - sizeBeforeCopy; - } } if (returnTargetLC.wasAccessed()) { diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java index abd2ad044a7a..354ad259c0c5 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java @@ -2,7 +2,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.List; import java.util.Map; import java.util.Set; import javax.lang.model.type.TypeMirror; @@ -64,21 +63,6 @@ return Collections.unmodifiableCollection(entryLabels.values()); } - /** - * Returns a new group that contains every type in the given groups. - * - * @param groups a list of groups for the same finally block; no type is in more than one of the - * groups - * @return a new group that contains every type in {@code groups}, in a deterministic order - */ - /*package-private*/ static RethrowGroup merge(List groups) { - RethrowGroup result = new RethrowGroup(); - for (RethrowGroup group : groups) { - result.entryLabels.putAll(group.entryLabels); - } - return result; - } - @Override public String toString() { return "RethrowGroup" + entryLabels; diff --git a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java index f0e6ee860e2c..c51d94aed377 100644 --- a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java +++ b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java @@ -43,29 +43,17 @@ public static void main(String[] args) { throw new Error("Expected 1 declared class, found " + cfg.getDeclaredClasses()); } - // Before the budget for extra exceptional copies of finally blocks is used up, each exception - // type gets its own copy, because each goes to a different catch block. + // Each exception type gets its own exceptional copy of the finally block, because each goes to + // a different catch block. cfg = CFGVisualizeLauncher.generateMethodCFG( - inputFile, "finallyCopiesBeforeBudgetIsUsedUp", clazz, /* analysis= */ null); + inputFile, "finallyCopyForEachCatchBlock", clazz, /* analysis= */ null); cfg.checkInvariants(); List copyEnds = exceptionalCopyEnds(cfg); if (copyEnds.size() != 3) { throw new Error("Expected 3 exceptional copies, found " + copyEnds.size()); } checkRethrowsToDistinctHandlers(copyEnds); - - // After the budget is used up, the exception types share one copy, which rethrows each of them - // to its own catch block. - cfg = - CFGVisualizeLauncher.generateMethodCFG( - inputFile, "finallyCopyAfterBudgetIsUsedUp", clazz, /* analysis= */ null); - cfg.checkInvariants(); - copyEnds = exceptionalCopyEnds(cfg); - if (copyEnds.size() != 1) { - throw new Error("Expected 1 shared exceptional copy, found " + copyEnds.size()); - } - checkRethrowsToDistinctHandlers(copyEnds); } /** diff --git a/dataflow/tests/cfgconstruction/Test.java b/dataflow/tests/cfgconstruction/Test.java index 0f1547e3fc15..4547c704d2f0 100644 --- a/dataflow/tests/cfgconstruction/Test.java +++ b/dataflow/tests/cfgconstruction/Test.java @@ -42,86 +42,10 @@ class Local {} void mightThrow() throws IOException {} - void log() {} - - // The finally block that assigns `finished` has one exceptional copy, which rethrows - // IOException, RuntimeException, and Error to three different catch blocks. The nested finally - // blocks before it use up CFGTranslationPhaseOne.EXTRA_EXCEPTIONAL_FINALLY_NODES_BUDGET. If the - // budget is increased, deepen their nesting so that they still use it up. This method is like - // the method in checker/tests/nullness/FinallyCopyBudget.java. - public void finallyCopyAfterBudgetIsUsedUp() { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - try { - try { - mightThrow(); - } finally { - log(); - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - } - } catch (IOException e) { - } - - boolean finished = false; - try { - try { - try { - try { - mightThrow(); - } finally { - finished = true; - } - } catch (IOException e) { - } - } catch (RuntimeException e) { - } - } catch (Error e) { - } - } - - // This method is like the end of the previous one. Because the budget is not used up, the - // finally block that assigns `finished` has three exceptional copies, one for each of - // IOException, RuntimeException, and Error. - public void finallyCopiesBeforeBudgetIsUsedUp() { + // The finally block that assigns `finished` has three exceptional copies, one for each of + // IOException, RuntimeException, and Error, because each of them is rethrown to a different + // catch block. + public void finallyCopyForEachCatchBlock() { boolean finished = false; try { try { From e91f062029b6affdd09126d26fe5021ee7ec3c72 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 13:56:27 -0800 Subject: [PATCH 84/98] Rename "entry label" to "copy-entry label"; use the term "finally-block copy"; clarify RethrowGroup documentation --- .../FinallyRethrowsException.java | 4 +- .../cfg/builder/CFGTranslationPhaseOne.java | 20 +++---- .../dataflow/cfg/builder/RethrowGroup.java | 58 ++++++++++--------- .../dataflow/cfg/builder/TryFinallyFrame.java | 10 ++-- .../java/cfgconstruction/CFGConstruction.java | 15 ++--- 5 files changed, 57 insertions(+), 50 deletions(-) diff --git a/checker/tests/resourceleak/FinallyRethrowsException.java b/checker/tests/resourceleak/FinallyRethrowsException.java index cbbdca70ed5c..b0a9c0a1cc52 100644 --- a/checker/tests/resourceleak/FinallyRethrowsException.java +++ b/checker/tests/resourceleak/FinallyRethrowsException.java @@ -159,8 +159,8 @@ void closedOnOneExceptionTypeFromOneNode() throws MyThrowable { void closedBeforeOtherExceptionToSameDestination() throws IOException, MyChecked { // A MyChecked exception reaches the finally block before r is allocated, and an IOException - // reaches it after r is closed. Both propagate out of the method, so one copy of the finally - // block serves both. r is closed on every path on which it is allocated. + // reaches it after r is closed. Both propagate out of the method, so one finally-block copy + // serves both. r is closed on every path on which it is allocated. QuietCloseable r = null; try { mightThrowMyChecked(); diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 269933fb021f..048972f731e1 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2853,8 +2853,8 @@ private void addCloseCallForResource(Tree resourceDeclarationTree, Void p) { * breaks, or continues) * @param finallyLabel label for the entry of the finally block for the normal case * @param exceptionalFinallyFrame the frame that the exceptions of the try block and of the catch - * blocks reach; its labels are the entries of the copies of the finally block for when the - * try block or a catch block throws an exception + * blocks reach; its labels are the entries of the finally-block copies for when the try block + * or a catch block throws an exception * @param finallyBlockCFGGenerator generates CFG nodes and edges for the finally block * @param oldReturnTargetLC old return target label cell, which gets restored to {@link * #returnTargetLC} while handling the finally block @@ -2900,10 +2900,10 @@ private void handleFinally( // `groups` partitions the types of the exceptions that the try block and the catch blocks // throw to this finally block (the one that `finallyBlockCFGGenerator` generates), that is, - // the exceptions that reach `exceptionalFinallyFrame`. For each group, a copy of this - // finally block starts at the group's entry labels, which exceptions of the group's types - // jump to when they reach this finally block, and the copy rethrows the group's types after - // this finally block completes normally. + // the exceptions that reach `exceptionalFinallyFrame`. For each group, a finally-block copy + // starts at the group's copy-entry labels, which exceptions of the group's types jump to when + // they reach this finally block, and the copy rethrows the group's types after the copy + // completes normally. // // For precision, two types share a copy if and only if the copy rethrows them to the same // places. The analysis merges the stores of the paths that reach a copy. Types that go to the @@ -2916,7 +2916,7 @@ private void handleFinally( // thrown while a resource is open is caught by a catch block that closes the resource, and // another exception, thrown after the resource is closed, propagates out of the method. for (RethrowGroup group : rethrowGroups(exceptionalFinallyFrame)) { - for (Label label : group.entryLabels()) { + for (Label label : group.copyEntryLabels()) { addLabelForNextNode(label); } String exceptionsString = group.types().toString(); @@ -3066,12 +3066,12 @@ private void handleFinally( } /** - * Returns the types of the exceptions that reach the given frame, grouped by where a copy of the - * finally block rethrows them. Two types are in the same group if and only if {@link + * Returns the types of the exceptions that reach the given frame, grouped by where a + * finally-block copy rethrows them. Two types are in the same group if and only if {@link * TryStack#possibleLabelsPastFinally} returns the same set of labels for each of them. * * @param frame a frame for a finally block, which the CFG builder has popped from the try stack - * @return the groups, in a deterministic order; the entry label of each type is its label in + * @return the groups, in a deterministic order; the copy-entry label of each type is its label in * {@code frame}. Empty if no exception reaches {@code frame}. */ private Collection rethrowGroups(TryFinallyFrame frame) { diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java index 354ad259c0c5..93615eb2daf5 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/RethrowGroup.java @@ -8,27 +8,32 @@ import org.plumelib.util.ArrayMap; /** - * A set of exception types that share one exceptional copy of a finally block. + * A set of exception types that share one exceptional finally-block copy. * - *

An exceptional copy of a finally block runs when an exception reaches the finally block (as - * defined in the documentation of {@link TryFinallyFrame}), and it rethrows the exception after the - * finally block completes normally. The types in a group, such as {@code java.io.IOException} and - * {@code java.lang.RuntimeException}, are some of the types of the exceptions that reach the - * finally block. + *

An exceptional finally-block copy is a copy of an original finally block. It runs when an + * exception reaches the original finally block (as defined in the documentation of {@link + * TryFinallyFrame}), and it rethrows the exception after the finally-block copy completes normally. + * The types in a group, such as {@code java.io.IOException} and {@code java.lang.RuntimeException}, + * are some of the types of the exceptions that reach the original finally block. * - *

For each of its types, a group stores the type's entry label: the label that the finally - * block's {@link TryFinallyFrame} sends the type to, which is the target of the exceptional edges - * for the type. The {@link TryFinallyFrame} creates the label (see {@link - * TryFinallyFrame#getExceptionLabels}), and the group stores a reference to the same label. The - * group's copy starts at the entry labels of all the types in the group. + *

For each type in a group, the group stores the type's copy-entry label: the label that the + * original finally block's {@link TryFinallyFrame} designates as the destination of exceptions of + * the type. The types in a group have different copy-entry labels, but all of them label one + * location in the CFG: the first node of the group's finally-block copy, where control enters the + * finally-block copy. The labels differ because the {@link TryFinallyFrame} creates one label for + * each type (see {@link TryFinallyFrame#getExceptionLabels}), before the CFG builder groups the + * types. When some node throws an exception that reaches the original finally block, control flows + * in the CFG along an exceptional edge from that node to the copy-entry label. The group stores + * references to the labels that the {@link TryFinallyFrame} creates. */ /*package-private*/ final class RethrowGroup { /** - * For each type in this group, its entry label. Like the map in {@link TryFinallyFrame}, it - * contains few entries. + * For each type in this group, its copy-entry label. Like the map in {@link TryFinallyFrame}, it + * maps few types. Every {@code Label} value labels the same location in the CFG: the first node + * of the group's finally-block copy. */ - private final Map entryLabels = new ArrayMap<>(); + private final Map copyEntryLabels = new ArrayMap<>(); /** Creates an empty RethrowGroup. */ /*package-private*/ RethrowGroup() {} @@ -36,13 +41,14 @@ /** * Adds the given type and label to this group. * - * @param type a type of exception that reaches the finally block and is not in this group - * @param entryLabel the label that the finally block's {@link TryFinallyFrame} sends {@code type} - * to: the target of the exceptional edges for {@code type} (see {@link - * TryFinallyFrame#getExceptionLabels}) + * @param type a type of exception that reaches the original finally block and is not in this + * group + * @param copyEntryLabel the copy-entry label of {@code type}: the label that the original finally + * block's {@link TryFinallyFrame} designates as the destination of exceptions of type {@code + * type} (see {@link TryFinallyFrame#getExceptionLabels}) */ - /*package-private*/ void add(TypeMirror type, Label entryLabel) { - entryLabels.put(type, entryLabel); + /*package-private*/ void add(TypeMirror type, Label copyEntryLabel) { + copyEntryLabels.put(type, copyEntryLabel); } /** @@ -51,20 +57,20 @@ * @return the types in this group, in a deterministic order */ /*package-private*/ Set types() { - return Collections.unmodifiableSet(entryLabels.keySet()); + return Collections.unmodifiableSet(copyEntryLabels.keySet()); } /** - * Returns the entry labels of the types in this group. + * Returns the copy-entry labels of the types in this group. * - * @return the entry labels of the types in this group, in the same order as {@link #types} + * @return the copy-entry labels of the types in this group, in the same order as {@link #types} */ - /*package-private*/ Collection

A type reaches a TryFinallyFrame if, while the frame is on the try stack, the CFG builder * creates a node that it records as possibly throwing that exact type, and no frame nearer the top @@ -41,8 +41,8 @@ * {@code java.lang.NullPointerException} and {@code java.lang.ArithmeticException}; the checked * exceptions in the {@code throws} clauses of the invoked methods and constructors; and the * static types of the expressions in {@code throw} statements, such as {@code - * java.io.IOException} for {@code throw new IOException()}. The copies of nested finally blocks - * rethrow types of these same kinds. + * java.io.IOException} for {@code throw new IOException()}. The finally-block copies of nested + * finally blocks rethrow types of these same kinds. */ private final Map exceptionLabels = new ArrayMap<>(); diff --git a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java index c51d94aed377..5ec34ba9b8d6 100644 --- a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java +++ b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java @@ -43,8 +43,8 @@ public static void main(String[] args) { throw new Error("Expected 1 declared class, found " + cfg.getDeclaredClasses()); } - // Each exception type gets its own exceptional copy of the finally block, because each goes to - // a different catch block. + // Each exception type gets its own exceptional finally-block copy, because each goes to a + // different catch block. cfg = CFGVisualizeLauncher.generateMethodCFG( inputFile, "finallyCopyForEachCatchBlock", clazz, /* analysis= */ null); @@ -57,12 +57,12 @@ public static void main(String[] args) { } /** - * Returns the blocks that end the exceptional copies of the finally block that assigns {@code - * finished}. Each such block rethrows the exceptions that its copy handles. + * Returns the blocks that end the exceptional finally-block copies whose original finally block + * assigns {@code finished}. Each such block rethrows the exceptions that its copy handles. * * @param cfg a control flow graph - * @return the blocks whose node is the marker at the end of an exceptional copy of the finally - * block that assigns {@code finished} + * @return the blocks whose node is the marker at the end of an exceptional finally-block copy + * whose original finally block assigns {@code finished} */ private static List exceptionalCopyEnds(ControlFlowGraph cfg) { List result = new ArrayList<>(); @@ -83,7 +83,8 @@ private static List exceptionalCopyEnds(ControlFlowGraph cfg) { * Checks that the given blocks together rethrow exactly IOException, RuntimeException, and Error, * each to a different catch block. * - * @param copyEnds the blocks that end the exceptional copies of a finally block + * @param copyEnds the blocks that end the exceptional finally-block copies of an original finally + * block */ private static void checkRethrowsToDistinctHandlers(List copyEnds) { Set typeNames = new HashSet<>(); From ff248ae470dbb215720203516dfce5a21aab57bf Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 14:10:49 -0800 Subject: [PATCH 85/98] Itemize the types that reach a TryFinallyFrame; say "finally-block copy" in the comment on sharing copies --- .../cfg/builder/CFGTranslationPhaseOne.java | 21 +++++++++-------- .../dataflow/cfg/builder/TryFinallyFrame.java | 23 ++++++++++++------- 2 files changed, 26 insertions(+), 18 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 048972f731e1..85200f2f8432 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2905,16 +2905,17 @@ private void handleFinally( // they reach this finally block, and the copy rethrows the group's types after the copy // completes normally. // - // For precision, two types share a copy if and only if the copy rethrows them to the same - // places. The analysis merges the stores of the paths that reach a copy. Types that go to the - // same places lose little precision by sharing a copy, because the analysis merges their stores - // at those places anyway. Sharing a copy merges the stores before the finally block rather - // than after it, which loses precision only if a transfer function in the finally block yields - // more precise results on the separate stores than on their merge. Types that go to different - // places get different copies, so that the analysis does not merge stores of paths that never - // meet. For example, the Resource Leak Checker would otherwise report a leak when an exception - // thrown while a resource is open is caught by a catch block that closes the resource, and - // another exception, thrown after the resource is closed, propagates out of the method. + // For precision, two types share a finally-block copy if and only if the copy rethrows them to + // the same places. The analysis merges the stores of the paths that reach a copy. Types that + // go to the same places lose little precision by sharing a copy, because the analysis merges + // their stores at those places anyway. Sharing a copy merges the stores before the finally + // block rather than after it, which loses precision only if a transfer function in the finally + // block yields more precise results on the separate stores than on their merge. Types that go + // to different places get different copies, so that the analysis does not merge stores of paths + // that never meet. For example, the Resource Leak Checker would otherwise report a leak when + // an exception thrown while a resource is open is caught by a catch block that closes the + // resource, and another exception, thrown after the resource is closed, propagates out of the + // method. for (RethrowGroup group : rethrowGroups(exceptionalFinallyFrame)) { for (Label label : group.copyEntryLabels()) { addLabelForNextNode(label); diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java index 6cabdc44e581..a64f419e757f 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/TryFinallyFrame.java @@ -35,14 +35,21 @@ * *

The keys are in a deterministic order, so the CFG is the same on every run. * - *

The map contains few entries, usually only a handful, so it is an {@link ArrayMap}. The - * types that reach a frame are {@code java.lang.RuntimeException} and {@code java.lang.Error}, - * which every invocation is recorded as possibly throwing; a few other unchecked types such as - * {@code java.lang.NullPointerException} and {@code java.lang.ArithmeticException}; the checked - * exceptions in the {@code throws} clauses of the invoked methods and constructors; and the - * static types of the expressions in {@code throw} statements, such as {@code - * java.io.IOException} for {@code throw new IOException()}. The finally-block copies of nested - * finally blocks rethrow types of these same kinds. + *

The map contains few entries, so it is an {@link ArrayMap}. The types that reach a frame + * are: + * + *

    + *
  • {@code java.lang.RuntimeException} and {@code java.lang.Error}, which every invocation is + * recorded as possibly throwing; + *
  • a few other unchecked types such as {@code java.lang.NullPointerException} and {@code + * java.lang.ArithmeticException}; + *
  • the checked exceptions in the {@code throws} clauses of the invoked methods and + * constructors; and + *
  • the static types of the expressions in {@code throw} statements, such as {@code + * java.io.IOException} for {@code throw new IOException()}. + *
+ * + *

The finally-block copies of nested finally blocks rethrow types of these same kinds. */ private final Map exceptionLabels = new ArrayMap<>(); From 9f5d0ed3e43acdb18ec15c01e987336171fac42e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 14:14:49 -0800 Subject: [PATCH 86/98] Describe the finally-rethrow change in the changelog; keep the original exception in the manual's workaround In the Resource Leak Checker manual's catch-and-rethrow workaround, an exception from close() is added as a suppressed exception (unless it is the original exception itself), so the caller still receives the original exception. --- docs/CHANGELOG.md | 9 +++++++++ docs/manual/resource-leak-checker.tex | 13 +++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 6ae236700726..116d5fc34ee4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,15 @@ ### User-visible changes +The CFG now preserves the types of the exceptions that propagate out of a +`finally` block, so the Resource Leak Checker reports leaks on exceptional +paths that it formerly missed. It still ignores the exception types that +`-AresourceLeakIgnoredExceptions` specifies, which by default include exactly +`RuntimeException` and exactly `Error`. It can report a false positive for a +`finally` block that closes a resource only if a boolean variable records that +the `try` block did not complete; the Resource Leak Checker manual gives a +workaround. + ### Changes for type system implementers `AnnotatedTypeFactory.binaryTreeArgTypes(AnnotatedTypeMirror, AnnotatedTypeMirror)` diff --git a/docs/manual/resource-leak-checker.tex b/docs/manual/resource-leak-checker.tex index 287e6b92ad17..8d407573b99c 100644 --- a/docs/manual/resource-leak-checker.tex +++ b/docs/manual/resource-leak-checker.tex @@ -627,7 +627,13 @@ initialize(c); // might throw IOException return c; } catch (Throwable t) { - c.close(); + try { + c.close(); + } catch (Throwable closeException) { + if (closeException != t) { + t.addSuppressed(closeException); + } + } throw t; } } @@ -636,9 +642,8 @@ \noindent Java permits \ in a method that is declared to throw only \, because the only checked exceptions that \ can hold are -those that the \ block can throw. -If \ itself throws an exception, that exception propagates -instead of \, just as in the version that uses \. +those that the \ block can throw. The inner \ ensures that if +\ also fails, the caller still receives the original exception. \sectionAndLabel{Errors about field initialization}{resource-leak-field-initialization} From 476b1d6e98467019c1ac8ed5c37487d529bc2f18 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 14:24:15 -0800 Subject: [PATCH 87/98] Do not give a string conversion exceptional edges --- dataflow/manual/content.tex | 2 -- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 10 +--------- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 6dc08274f137..762e73c31a53 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -950,8 +950,6 @@ \subsection{Formal Definition of the Control-Flow Graph} \code{ClassNameNode} & \code{ClassCircularityError}, \code{ClassFormatError}, \\ & \code{NoClassDefFoundError}, \code{OutOfMemoryError} \\ \code{FunctionalInterfaceNode} & \code{NullPointerException} (bound method reference \code{e::m}) \\ - \code{StringConversionNode} & \code{RuntimeException}, \code{Error} (operand of reference type, \\ - & whose \code{toString} is invoked) \\ \code{MarkerNode} & Types rethrown at the end of a \code{finally} block; \\ & \code{IllegalArgumentException} (synthetic \code{addSuppressed} in \\ & try-with-resources) \\ diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index b2e32239669a..276583b58d38 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1007,15 +1007,7 @@ protected Node stringConversion(Node node) { if (!TypesUtils.isString(node.getType())) { Node converted = new StringConversionNode(node.getTree(), node, stringType); addToImplicitlyConvertedLookupMap(converted); - TypeMirror type = node.getType(); - if (type.getKind().isPrimitive() - || type.getKind() == TypeKind.NULL - || TypesUtils.isBoxedPrimitive(type)) { - insertNodeAfter(converted, node); - } else { - // The conversion may invoke an arbitrary toString() method, which may throw. - insertNodeWithExceptionsAfter(converted, uncheckedExceptionTypes, node); - } + insertNodeAfter(converted, node); return converted; } else { return node; From 169a38147a2bc7857f881b5a1c9f3fa57c1c8531 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 28 Nov 2026 23:25:07 -0800 Subject: [PATCH 88/98] Keep the receiver NullPointerException on the failure path of an instance @AssertMethod The receiver is tested for nullness after the arguments are evaluated, but for an @AssertMethod the path on which the assertion fails does not reach the method access. Give that path its own NullPointerException edge when the receiver may be null. Add a test whose outcome depends on the method access's NullPointerException edge being after the argument evaluation. --- .../nullness/ReceiverRefinementInCatch.java | 28 ++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 65 +++++++++++++++++-- .../flow/ReceiverNullPointerException.java | 5 +- 3 files changed, 91 insertions(+), 7 deletions(-) diff --git a/checker/tests/nullness/ReceiverRefinementInCatch.java b/checker/tests/nullness/ReceiverRefinementInCatch.java index 8f26f2a5197e..16946e8425f3 100644 --- a/checker/tests/nullness/ReceiverRefinementInCatch.java +++ b/checker/tests/nullness/ReceiverRefinementInCatch.java @@ -14,6 +14,34 @@ void m(@Nullable Object o) { } } + // The receiver is tested for nullness after the argument is evaluated, so p is non-null in the + // handler. The only path on which o may be null in the handler is the NullPointerException for + // a null receiver; every other exceptional successor of the call has a non-null receiver. + void receiverTestedAfterArgument(@Nullable Object o, @Nullable Object p) { + try { + // :: error: (dereference.of.nullable) + o.equals(p = ""); + } catch (NullPointerException e) { + p.toString(); + // :: error: (dereference.of.nullable) + o.hashCode(); + } + } + + @org.checkerframework.dataflow.qual.AssertMethod + void check(boolean b) {} + + // If r is null, the call throws a NullPointerException whether or not the assertion fails. + void assertMethodWithNullReceiver(@Nullable ReceiverRefinementInCatch r, @Nullable Object o) { + try { + // :: error: (dereference.of.nullable) + r.check(o != null); + } catch (NullPointerException e) { + // :: error: (dereference.of.nullable) + o.toString(); + } + } + void read() throws java.io.IOException {} // A null receiver causes a NullPointerException, which a handler for IOException does not catch. diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 276583b58d38..21c48df2d7d5 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1330,6 +1330,31 @@ protected List convertCallArguments( ExecutableElement method, ExecutableType methodType, List actualExprs) { + return convertCallArguments(tree, method, methodType, actualExprs, false); + } + + /** + * Given a method element, its type at the call site, and a list of argument expressions, return + * a list of {@link Node}s representing the arguments converted for a call of the method, as + * {@link #convertCallArguments(ExpressionTree, ExecutableElement, ExecutableType, List)} does. + * + * @param tree the invocation tree for the call + * @param method an ExecutableElement representing a method to be called + * @param methodType an ExecutableType representing the type of the method call; the type must be + * viewpoint-adapted to the call + * @param actualExprs a List of argument expressions to a call + * @param nullReceiverThrows true if the call has a receiver that may be null, in which case the + * call throws a {@code NullPointerException} instead of invoking the method; used if the + * method is an {@link AssertMethod} + * @return a List of {@link Node}s representing arguments after conversions required by a call to + * this method + */ + private List convertCallArguments( + ExpressionTree tree, + ExecutableElement method, + ExecutableType methodType, + List actualExprs, + boolean nullReceiverThrows) { // NOTE: It is important to convert one method argument before generating CFG nodes for the // next argument, since label binding expects nodes to be generated in execution order. // Therefore, this method first determines which conversions need to be applied and then @@ -1354,7 +1379,8 @@ protected List convertCallArguments( for (int i = 0; i < numActuals; i++) { Node actualVal = scan(actualExprs.get(i), null); if (i == assertMethodTuple.booleanParam) { - treatMethodAsAssert((MethodInvocationTree) tree, assertMethodTuple, actualVal); + treatMethodAsAssert( + (MethodInvocationTree) tree, assertMethodTuple, actualVal, nullReceiverThrows); } if (actualVal == null) { throw new BugInCF( @@ -1370,7 +1396,8 @@ protected List convertCallArguments( for (int i = 0; i < lastArgIndex; i++) { Node actualVal = scan(actualExprs.get(i), null); if (i == assertMethodTuple.booleanParam) { - treatMethodAsAssert((MethodInvocationTree) tree, assertMethodTuple, actualVal); + treatMethodAsAssert( + (MethodInvocationTree) tree, assertMethodTuple, actualVal, nullReceiverThrows); } convertedNodes.add(methodInvocationConvert(actualVal, formals.get(i))); } @@ -1402,7 +1429,8 @@ protected List convertCallArguments( for (int i = 0; i < numActuals; i++) { Node actualVal = scan(actualExprs.get(i), null); if (i == assertMethodTuple.booleanParam) { - treatMethodAsAssert((MethodInvocationTree) tree, assertMethodTuple, actualVal); + treatMethodAsAssert( + (MethodInvocationTree) tree, assertMethodTuple, actualVal, nullReceiverThrows); } convertedNodes.add(methodInvocationConvert(actualVal, formals.get(i))); } @@ -3674,6 +3702,26 @@ protected void translateAssertWithAssertionsEnabled(AssertTree tree) { */ protected void treatMethodAsAssert( MethodInvocationTree tree, AssertMethodTuple assertMethodTuple, Node condition) { + treatMethodAsAssert(tree, assertMethodTuple, condition, false); + } + + /** + * Translates a method marked as {@link AssertMethod} into CFG nodes corresponding to an {@code + * assert} statement, as {@link #treatMethodAsAssert(MethodInvocationTree, AssertMethodTuple, + * Node)} does. + * + * @param tree the method invocation tree for a method marked as {@link AssertMethod} + * @param assertMethodTuple the assert method tuple for the method + * @param condition the boolean expression node for the argument that the method tests + * @param nullReceiverThrows true if the call has a receiver that may be null. Then, on the path + * on which the assertion fails, the call may throw a {@code NullPointerException} instead of + * invoking the method. (On the other path, the call's method access throws it.) + */ + private void treatMethodAsAssert( + MethodInvocationTree tree, + AssertMethodTuple assertMethodTuple, + Node condition, + boolean nullReceiverThrows) { // all necessary labels Label thenLabel = new Label(); @@ -3684,7 +3732,7 @@ protected void treatMethodAsAssert( addLabelForNextNode(assertMethodTuple.isAssertFalse ? thenLabel : elseLabel); AssertionErrorNode assertNode = new AssertionErrorNode(tree, condition, null, assertMethodTuple.exceptionType); - extendWithNode(assertNode); + extendWithNode(assertNode, nullReceiverThrows); NodeWithExceptionsHolder exNode = extendWithNodeWithException( new ThrowNode(null, assertNode, env.getTypeUtils()), assertMethodTuple.exceptionType); @@ -3720,6 +3768,7 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi Node receiver = getReceiver(methodSelect); MethodAccessNode target = new MethodAccessNode(methodSelect, method, receiver); + boolean nullReceiverThrows = accessMayThrowNullPointerException(method, receiver); List arguments; if (TreeUtils.isEnumSuperCall(tree)) { @@ -3731,14 +3780,18 @@ public MethodInvocationNode visitMethodInvocation(MethodInvocationTree tree, Voi // See also BaseTypeVisitor.visitMethodInvocation and QualifierPolymorphism.annotate. arguments = Collections.emptyList(); } else { - arguments = convertCallArguments(tree, method, TreeUtils.typeFromUse(tree), actualExprs); + // For an AssertMethod, the path on which the assertion fails does not reach `target`, so + // that path gets its own NullPointerException edge for a null receiver. + arguments = + convertCallArguments( + tree, method, TreeUtils.typeFromUse(tree), actualExprs, nullReceiverThrows); } // Look up the method to invoke, which tests the receiver for nullness after the arguments are // evaluated. The NullPointerException for a null receiver is thrown here rather than by the // MethodInvocationNode, so its exceptional store is the one before the call, without any // postcondition of the method, which never ran. - extendWithNode(target, accessMayThrowNullPointerException(method, receiver)); + extendWithNode(target, nullReceiverThrows); // TODO: lock the receiver for synchronized methods diff --git a/framework/tests/flow/ReceiverNullPointerException.java b/framework/tests/flow/ReceiverNullPointerException.java index 13048abb2cb9..463d715c86a0 100644 --- a/framework/tests/flow/ReceiverNullPointerException.java +++ b/framework/tests/flow/ReceiverNullPointerException.java @@ -293,7 +293,10 @@ void methodCallMayBeNull(@Odd String p1, String p2, String s) { } // The call has an exceptional edge after its argument is evaluated. No other node in the try - // block can throw a NullPointerException after `l1 = p2`. + // block can throw a NullPointerException after `l1 = p2`. The call's own exceptional edges reach + // the handler with the same store as its receiver test, so this test does not distinguish them; + // method receiverTestedAfterArgument in checker/tests/nullness/ReceiverRefinementInCatch.java + // does. void methodCallMayBeNullAfterArgument(@Odd String p1, String p2, String s) { String l1 = p1; try { From 95e778cc25922a952626e55bed5c5db11893ebea Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 15:48:48 -0800 Subject: [PATCH 89/98] Reformat a Javadoc comment --- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 21c48df2d7d5..67d10111699d 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1334,9 +1334,9 @@ protected List convertCallArguments( } /** - * Given a method element, its type at the call site, and a list of argument expressions, return - * a list of {@link Node}s representing the arguments converted for a call of the method, as - * {@link #convertCallArguments(ExpressionTree, ExecutableElement, ExecutableType, List)} does. + * Given a method element, its type at the call site, and a list of argument expressions, return a + * list of {@link Node}s representing the arguments converted for a call of the method, as {@link + * #convertCallArguments(ExpressionTree, ExecutableElement, ExecutableType, List)} does. * * @param tree the invocation tree for the call * @param method an ExecutableElement representing a method to be called From 41c9352aef335f54da318a7b40751536124ad016 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 22:15:55 -0800 Subject: [PATCH 90/98] Use the effective throws clause of close() when deciding whether a try-with-resources may self-suppress --- .../TryWithResourcesSelfSuppression.java | 57 ++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 105 +++++++++++++++++- 2 files changed, 158 insertions(+), 4 deletions(-) diff --git a/checker/tests/nullness/TryWithResourcesSelfSuppression.java b/checker/tests/nullness/TryWithResourcesSelfSuppression.java index 95cf67bc12b4..a7a22629666f 100644 --- a/checker/tests/nullness/TryWithResourcesSelfSuppression.java +++ b/checker/tests/nullness/TryWithResourcesSelfSuppression.java @@ -124,6 +124,63 @@ void selfSuppressionForGenericResource(GenericResource r, MyExcepti } } + interface ResourceThrowingOtherException extends AutoCloseable { + @Override + void close() throws OtherException; + } + + // The effective throws clause of close() is empty: it is the intersection of the clauses of the + // two inherited declarations. + interface ResourceThrowingNothing + extends ResourceThrowingMyException, ResourceThrowingOtherException {} + + void noSelfSuppressionForTwoInheritedCloseMethods(ResourceThrowingNothing r, MyException ex) + throws MyException { + @Nullable Object o = ""; + try { + try (r) { + try { + o = null; + throw ex; + } catch (RuntimeException | Error e) { + o = ""; + return; + } + } + } catch (IllegalArgumentException e) { + // close() cannot throw a MyException, so it cannot throw the primary exception. + o.toString(); + } + } + + // Both inherited declarations of close() allow a MyException. + interface ResourceThrowingException extends AutoCloseable { + @Override + void close() throws Exception; + } + + interface ResourceThrowingMyExceptionTwice + extends ResourceThrowingMyException, ResourceThrowingException {} + + void selfSuppressionForTwoInheritedCloseMethods( + ResourceThrowingMyExceptionTwice r, MyException ex) throws MyException { + @Nullable Object o = ""; + try { + try (r) { + try { + o = null; + throw ex; + } catch (RuntimeException | Error e) { + o = ""; + return; + } + } + } catch (IllegalArgumentException e) { + // :: error: (dereference.of.nullable) + o.toString(); + } + } + // A MyException and an OtherException reach the same catch clause, but only a MyException can be // the exception that close() throws. So they get different copies of the synthetic finally // block, and only the copy for MyException, in which o is non-null, reaches the diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index dd04edb5050d..9a304d3cb321 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -80,16 +80,19 @@ 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.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; +import javax.lang.model.type.IntersectionType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.ReferenceType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import org.checkerframework.checker.interning.qual.FindDistinct; @@ -2961,6 +2964,12 @@ private void addSuppressingCloseCallForResource( * R} and {@code R} declares {@code void close() throws E}, the * result is {@code [IOException]}, not {@code [E]}. * + *

If the type of the resource inherits {@code close} from several interfaces, the result is + * the effective {@code throws} clause of {@code close} (JLS 9.4.1.3): the types that are thrown + * by one declaration and allowed by every other declaration. For example, if the type inherits + * {@code void close() throws IOException} and {@code void close() throws SQLException}, the + * result is empty. + * * @param resourceDeclarationTree the resource declaration, or the variable or field that is the * resource * @return the types in the {@code throws} clause of {@code close}, as a member of the type of the @@ -2972,14 +2981,102 @@ private List closeThrownTypes(Tree resourceDeclarationTree if (closeMethod == null) { throw new BugInCF("no close method for %s of type %s", resourceDeclarationTree, resourceType); } - if (TypesUtils.upperBound(resourceType) instanceof DeclaredType declaredType) { + TypeMirror upperBound = TypesUtils.upperBound(resourceType); + List thrownTypes = closeMethod.getThrownTypes(); + if (upperBound instanceof DeclaredType declaredType) { try { - return ((ExecutableType) types.asMemberOf(declaredType, closeMethod)).getThrownTypes(); + ExecutableType closeType = (ExecutableType) types.asMemberOf(declaredType, closeMethod); + thrownTypes = closeType.getThrownTypes(); } catch (IllegalArgumentException e) { - // The declared type does not have `closeMethod` as a member; fall through. + // The declared type does not have `closeMethod` as a member; keep the declared throws + // clause. + } + } + // A close method of a class overrides the close methods of the interfaces, and its throws clause + // must be compatible with theirs, so its throws clause is the effective one. Only a method of + // an interface might be one of several inherited declarations. + if (!closeMethod.getEnclosingElement().getKind().isInterface()) { + return thrownTypes; + } + List> clauses = interfaceCloseThrownTypes(upperBound); + if (clauses.size() <= 1) { + return thrownTypes; + } + // Including the throws clause of an overridden declaration does not change the result, because + // every type that an overriding declaration throws is allowed by the overridden declaration. + List result = new ArrayList<>(); + for (List clause : clauses) { + for (TypeMirror thrownType : clause) { + if (allowedByEveryClause(thrownType, clauses) + && !CollectionsP.anyMatch(result, t -> types.isSameType(t, thrownType))) { + result.add(thrownType); + } + } + } + return result; + } + + /** + * Returns the {@code throws} clauses of the no-argument {@code close} methods that interfaces + * among {@code type} and its supertypes declare, each as a member of the supertype that declares + * it. + * + * @param type a type, which may be an intersection type + * @return the {@code throws} clauses of the {@code close} methods of the interfaces among {@code + * type} and its supertypes + */ + private List> interfaceCloseThrownTypes(TypeMirror type) { + List> result = new ArrayList<>(); + Set visited = new HashSet<>(); + List worklist = new ArrayList<>(); + worklist.add(type); + while (!worklist.isEmpty()) { + TypeMirror t = worklist.remove(worklist.size() - 1); + if (t instanceof IntersectionType intersectionType) { + worklist.addAll(intersectionType.getBounds()); + continue; + } + if (!(t instanceof DeclaredType declaredType)) { + continue; + } + Element typeElement = declaredType.asElement(); + if (!visited.add(typeElement)) { + continue; + } + if (typeElement.getKind().isInterface()) { + List members = typeElement.getEnclosedElements(); + for (ExecutableElement method : ElementFilter.methodsIn(members)) { + if (method.getSimpleName().contentEquals("close") + && method.getParameters().isEmpty() + && !method.getModifiers().contains(Modifier.STATIC) + && !method.getModifiers().contains(Modifier.PRIVATE)) { + result.add(((ExecutableType) types.asMemberOf(declaredType, method)).getThrownTypes()); + } + } + } + worklist.addAll(types.directSupertypes(declaredType)); + } + return result; + } + + /** + * Returns true if every {@code throws} clause in {@code clauses} allows {@code thrownType}: that + * is, if each clause contains a supertype of {@code thrownType}. + * + * @param thrownType a type in one of {@code clauses} + * @param clauses {@code throws} clauses + * @return true if every clause in {@code clauses} allows {@code thrownType} + */ + private boolean allowedByEveryClause( + TypeMirror thrownType, List> clauses) { + // Erasure replaces a type variable, such as one in a throws clause, by its upper bound. + TypeMirror thrownErased = types.erasure(thrownType); + for (List clause : clauses) { + if (!CollectionsP.anyMatch(clause, t -> types.isSubtype(thrownErased, types.erasure(t)))) { + return false; } } - return closeMethod.getThrownTypes(); + return true; } /** From 19fef13d6237dbe2f94ea58e57c556ae9245c2a2 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 22:30:31 -0800 Subject: [PATCH 91/98] Keep receiver refinement that the store's side-effect analysis preserves; resolve iterator() return type at the loop site When the invoked method might have side effects, refine the receiver in the store before the invocation, so that the store's updateForMethodCall (which accounts for @SideEffectsOnly, monotonic fields, and unassignable fields) decides whether the refinement survives. Skip the exceptional-store copy for a this or super receiver. For an enhanced for loop in an argument, use the return type of iterator() as a member of the loop expression's type, so a type variable is resolved to its type argument. Make the resource-declaration test depend only on close(). --- .../checker/nullness/NullnessTransfer.java | 68 +++++++++++++++---- .../ReceiverRefinementSideEffectsOnly.java | 45 ++++++++++++ .../ReceiverReassignedByImplicitCall.java | 37 +++++++++- 3 files changed, 137 insertions(+), 13 deletions(-) create mode 100644 checker/tests/nullness/ReceiverRefinementSideEffectsOnly.java diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 235e5ed53520..6d025006c2a0 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -24,6 +24,8 @@ import javax.lang.model.element.RecordComponentElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; @@ -44,6 +46,8 @@ import org.checkerframework.dataflow.cfg.node.Node; import org.checkerframework.dataflow.cfg.node.NullLiteralNode; import org.checkerframework.dataflow.cfg.node.ReturnNode; +import org.checkerframework.dataflow.cfg.node.SuperNode; +import org.checkerframework.dataflow.cfg.node.ThisNode; import org.checkerframework.dataflow.cfg.node.ThrowNode; import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.dataflow.expression.LocalVariable; @@ -418,11 +422,12 @@ public TransferResult visitThrow( * that are passed to non-null parameters in a method call or constructor invocation are unsoundly * assumed to be non-null after the invocation. * - *

When the flag is turned off, the analysis is sound: it checks that the method is - * SideEffectFree or the receiver is unassignable. Only if either one of the two is true is the - * receiver made non-null. The receiver is also made non-null if the method is annotated {@link - * org.checkerframework.framework.qual.DoesNotUnrefineReceiver}. Similar logic is applied to the - * arguments of the invocation. + *

When the flag is turned off, the analysis is sound: the receiver is made non-null only if + * the method is SideEffectFree, the receiver is unassignable, the method is annotated {@link + * org.checkerframework.framework.qual.DoesNotUnrefineReceiver}, or the store's handling of method + * side effects (which accounts for {@link org.checkerframework.dataflow.qual.SideEffectsOnly}) + * determines that the method cannot change the receiver expression. Similar logic is applied to + * the arguments of the invocation. * *

The receiver of a static method invocation is never made non-null, because the invocation * does not dereference it. @@ -453,22 +458,39 @@ public TransferResult visitMethodInvocation( // that has no tree, whose arguments cannot be examined. // A method annotated @DoesNotUnrefineReceiver does not reassign its receiver expression. JavaExpression receiverExpr = JavaExpression.fromNode(receiver); - boolean refineReceiver = + boolean receiverMayBeRefined = !n.getTarget().isStatic() + && tree != null + && !argumentsMayReassign(tree.getArguments(), receiverExpr); + // True if the invoked method cannot make the receiver expression null. + boolean refineReceiver = + receiverMayBeRefined && (nonNullAssumptionAfterInvocation || isMethodSideEffectFree || atypeFactory.hasDoesNotUnrefineReceiver(method) - || !mayChangeByOtherCode(receiverExpr)) - && tree != null - && !argumentsMayReassign(tree.getArguments(), receiverExpr); + || !mayChangeByOtherCode(receiverExpr)); // The exceptional successors of the invocation get the store before the invocation, which - // super.visitMethodInvocation modifies in place. So, copy it first. + // super.visitMethodInvocation modifies in place. So, copy it first. A `this` or `super` + // receiver is always non-null, so its exceptional successors need no refinement. @Nullable NullnessStore storeBeforeInvocation = - refineReceiver && n.getBlock() instanceof ExceptionBlock + refineReceiver + && n.getBlock() instanceof ExceptionBlock + && !(receiver instanceof ThisNode) + && !(receiver instanceof SuperNode) ? in.getRegularStore().copy() : null; + if (receiverMayBeRefined && !refineReceiver && !in.containsTwoStores()) { + // The invoked method might make the receiver expression null. Refine the receiver in the + // store before the invocation, so that super.visitMethodInvocation discards the refinement + // exactly if the store's side-effect analysis (for example, of a @SideEffectsOnly + // annotation) determines that the invoked method might change the receiver expression. + // The exceptional successors do not see this refinement, because they get the store before + // the invocation from the analysis rather than from `in`. + makeNonNull(in.getRegularStore(), receiver); + } + TransferResult result = super.visitMethodInvocation(n, in); if (refineReceiver) { @@ -715,7 +737,7 @@ public Boolean visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { return true; } for (ExecutableElement iteratorMethod : iteratorMethods) { - TypeMirror iteratorType = iteratorMethod.getReturnType(); + TypeMirror iteratorType = returnTypeAsMemberOf(iterableType, iteratorMethod); if (mayHaveSideEffect(iteratorMethod) || noArgMethodMayHaveSideEffect(iteratorType, "hasNext", null) || noArgMethodMayHaveSideEffect(iteratorType, "next", null)) { @@ -830,6 +852,28 @@ private boolean noArgMethodMayHaveSideEffect( return false; } + /* + * Returns the return type of the given method, as a member of the given type. For + * example, if {@code iterator()} is declared to return a type variable {@code I}, then + * the result for the type {@code Items} is {@code PureIterator} rather + * than {@code I}, whose erasure is its bound. If {@code type} is not a declared type, + * returns the declared return type, whose methods are no more pure than those of the + * actual return type. + * + * @param type the static type of the receiver of an invocation of {@code method} + * @param method a method that is a member of {@code type} + * @return the return type of {@code method}, as a member of {@code type} + */ + private TypeMirror returnTypeAsMemberOf(TypeMirror type, ExecutableElement method) { + if (type.getKind() == TypeKind.DECLARED) { + TypeMirror memberType = analysis.getTypes().asMemberOf((DeclaredType) type, method); + if (memberType.getKind() == TypeKind.EXECUTABLE) { + return ((ExecutableType) memberType).getReturnType(); + } + } + return method.getReturnType(); + } + /* * Returns the no-argument methods with the given name that are members (declared or * inherited) of the erasure of the given type, omitting each method that another of diff --git a/checker/tests/nullness/ReceiverRefinementSideEffectsOnly.java b/checker/tests/nullness/ReceiverRefinementSideEffectsOnly.java new file mode 100644 index 000000000000..c954aec1cbf8 --- /dev/null +++ b/checker/tests/nullness/ReceiverRefinementSideEffectsOnly.java @@ -0,0 +1,45 @@ +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.SideEffectsOnly; + +// After a call completes normally, its receiver is non-null, unless the call might have made the +// receiver expression null. A @SideEffectsOnly annotation limits what the call might change. +public class ReceiverRefinementSideEffectsOnly { + + static class Counter { + int count; + + @SideEffectsOnly("this.count") + void bump() { + count++; + } + + @SideEffectsOnly("#1.f") + void clear(ReceiverRefinementSideEffectsOnly holder) { + holder.f = null; + } + + void unannotated() {} + } + + @Nullable Counter f; + + void sideEffectsOnlyOtherState() { + // :: error: (dereference.of.nullable) + f.bump(); + f.toString(); + } + + void sideEffectsOnlyReceiverHolder() { + // :: error: (dereference.of.nullable) + f.clear(this); + // :: error: (dereference.of.nullable) + f.toString(); + } + + void arbitrarySideEffects() { + // :: error: (dereference.of.nullable) + f.unannotated(); + // :: error: (dereference.of.nullable) + f.toString(); + } +} diff --git a/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java index 69bcc4c1e442..17a32d0c36c1 100644 --- a/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java +++ b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java @@ -43,11 +43,13 @@ void resourceCloseClearsReceiver(int tag) { } void resourceDeclarationCloseClearsReceiver(int tag) { + // Construct the resource outside the argument, so that only close() might reassign f. + ClearingResource resource = new ClearingResource(); // :: error: (dereference.of.nullable) f.take( switch (tag) { default -> { - try (ClearingResource resource = new ClearingResource()) {} + try (ClearingResource alias = resource) {} yield 0; } }); @@ -200,6 +202,39 @@ void iteratorIsPure(int tag, PureItems items) { f.toString(); } + abstract class GenericItems implements Iterable { + @Override + @SideEffectFree + public abstract I iterator(); + } + + // The loop uses a PureIterator, though iterator() is declared to return I, whose bound is + // BaseIterator. + void genericIteratorIsPure(int tag, GenericItems items) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + for (Object ignored : items) {} + yield 0; + } + }); + f.toString(); + } + + void genericIteratorClearsReceiver(int tag, GenericItems items) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + for (Object ignored : items) {} + yield 0; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } + // BaseIterator.next() might reassign f. void nextClearsReceiver(int tag, ClearingItems items) { // :: error: (dereference.of.nullable) From 7d3a7d1966e7952645b867639ccedcfafbd12484 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 22:30:31 -0800 Subject: [PATCH 92/98] Test that the NullPointerException handler for `throw null` is reachable --- checker/tests/nullness/Exceptions.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/checker/tests/nullness/Exceptions.java b/checker/tests/nullness/Exceptions.java index d9434fc7900e..855cd66e9bc2 100644 --- a/checker/tests/nullness/Exceptions.java +++ b/checker/tests/nullness/Exceptions.java @@ -54,6 +54,19 @@ void throwNullInTryCatch() { } } + // The code after the try statement is reachable only through the NullPointerException handler, + // where `o` is non-null. If the handler were unreachable, `o` would have its declared type. + void throwNullReachesHandler() { + @Nullable Object o = null; + try { + // :: error: [throwing.nullable] + throw null; + } catch (NullPointerException e) { + o = ""; + } + o.toString(); + } + void throwNullInTryFinallyInTryCatch() { try { try { From 74ab44b393e06c1d1e8603175955a1773d2b69cd Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 22:38:46 -0800 Subject: [PATCH 93/98] Dataflow Manual: the most-specific-edge rule does not govern getAnyExceptionTypes() edges --- dataflow/manual/content.tex | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/dataflow/manual/content.tex b/dataflow/manual/content.tex index 9e7d2fd5e0d9..7da7b42b35fd 100644 --- a/dataflow/manual/content.tex +++ b/dataflow/manual/content.tex @@ -712,6 +712,19 @@ \subsection{Formal Definition of the Control-Flow Graph} the execution takes the first edge only if the exception is of a subtype of \code{A}, but not a subtype of \code{B}. + This most-specific-edge rule does not govern the edges labeled + by the types in + \code{MethodInvocationNode.getAnyExceptionTypes()}. The + invocation may follow such an edge whenever it throws an + exception, whatever the type of that exception. For example, a + synthetic \code{close()} call of a try-with-resources statement + on a path on which an \code{IOException} is pending may throw an + \code{Error} and still follow an edge labeled + \code{IOException}. So the label of such an edge need not + describe the thrown exception, and a fact that holds only when + the invoked method throws an exception of a particular type, such + as an exceptional postcondition, does not hold on such an edge. + \begin{workinprogress} There is not necessarily a most specific exception type in the program text; in that case, does the translation add a most specific case that will From 8ff07ffb5110c00288a5273971fa565b93bb04f8 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 22:38:56 -0800 Subject: [PATCH 94/98] Give synthetic iterator-protocol method accesses a NullPointerException edge The method accesses of the iterator(), hasNext(), and next() calls that an enhanced for loop desugars to now throw the NullPointerException for a null receiver, as the method access of a call in source code does. So every exceptional successor of a synthetic invocation has a non-null receiver, and NullnessTransfer refines the receiver on all of them. A handler that cannot catch a NullPointerException, such as one for IllegalArgumentException, keeps the non-null fact. Document that on the failure path of an @AssertMethod, the receiver's NullPointerException, like the AssertionError, precedes the evaluation of later arguments. --- .../checker/nullness/NullnessTransfer.java | 44 +++++++------------ .../nullness/ReceiverRefinementInCatch.java | 23 ++++++++++ .../cfg/builder/CFGTranslationPhaseOne.java | 15 +++++-- 3 files changed, 50 insertions(+), 32 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 6d025006c2a0..62e5a411cc99 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -19,6 +19,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.RecordComponentElement; @@ -117,9 +118,6 @@ public class NullnessTransfer */ private final boolean nonNullAssumptionAfterInvocation; - /** The type {@code java.lang.NullPointerException}. */ - private final TypeMirror nullPointerExceptionType; - /** The method {@code Object.toString()}. */ private final ExecutableElement objectToString; @@ -160,9 +158,6 @@ public NullnessTransfer(NullnessAnalysis analysis) { .getChecker() .getBooleanOption("invocationPreservesArgumentNullness", true); - nullPointerExceptionType = - TypesUtils.typeFromClass(NullPointerException.class, analysis.getTypes(), elements); - objectToString = TreeUtils.getMethod("java.lang.Object", "toString", 0, analysis.getEnv()); } @@ -555,24 +550,19 @@ public TransferResult visitMethodInvocation( * Returns a transfer result like {@code result}, in which the receiver of {@code n} is non-null * on exceptional successors of {@code n}. * - *

For an invocation in source code, the receiver is non-null on every exceptional successor. - * Its {@code NullPointerException} for a null receiver comes from its {@code MethodAccessNode}, - * not from {@code n}. So every exception that {@code n} throws comes from the invoked method, - * which the invocation entered only because the receiver is non-null. A handler that the {@code - * MethodAccessNode}'s {@code NullPointerException} edge reaches, such as a handler for {@code - * NullPointerException} or {@code RuntimeException}, merges in the unrefined store from that - * edge, so the receiver is not non-null there. - * - *

For a synthetic invocation, the receiver is non-null only on each exceptional successor - * whose exception type excludes {@code NullPointerException}, such as a handler for a checked - * exception that the invoked method declares. A synthetic invocation, such as the {@code - * iterator()} call of an enhanced {@code for} loop, can throw the {@code NullPointerException} - * for a null receiver itself. + *

The receiver is non-null on every exceptional successor. The {@code NullPointerException} + * for a null receiver comes from the invocation's {@code MethodAccessNode}, not from {@code n}. + * That holds both for an invocation in source code and for a synthetic invocation, such as the + * {@code iterator()} call of an enhanced {@code for} loop. So every exception that {@code n} + * throws comes from the invoked method, which the invocation entered only because the receiver is + * non-null. A handler that the {@code MethodAccessNode}'s {@code NullPointerException} edge + * reaches, such as a handler for {@code NullPointerException} or {@code RuntimeException}, merges + * in the unrefined store from that edge, so the receiver is not non-null there. * * @param n a method invocation whose receiver should be refined * @param result the transfer result for {@code n} * @param storeBefore the store before {@code n}; is not side-effected - * @return a transfer result like {@code result}, with the receiver refined on some exceptional + * @return a transfer result like {@code result}, with the receiver refined on the exceptional * successors */ private TransferResult refineReceiverOnExceptionalSuccessors( @@ -586,20 +576,18 @@ private TransferResult refineReceiverOnExceptional Map oldExceptionalStores = result.getExceptionalStores(); Map newExceptionalStores = oldExceptionalStores == null ? new HashMap<>() : new HashMap<>(oldExceptionalStores); - boolean refined = false; - boolean isInSource = n.getInSource(); - for (TypeMirror exceptionType : exceptionBlock.getExceptionalSuccessors().keySet()) { - if (!isInSource && analysis.getTypes().isSubtype(nullPointerExceptionType, exceptionType)) { - continue; - } + Set exceptionTypes = exceptionBlock.getExceptionalSuccessors().keySet(); + if (exceptionTypes.isEmpty()) { + return result; + } + for (TypeMirror exceptionType : exceptionTypes) { NullnessStore exceptionalStore = newExceptionalStores.get(exceptionType); NullnessStore refinedStore = (exceptionalStore == null ? storeBefore : exceptionalStore).copy(); makeNonNull(refinedStore, receiver); newExceptionalStores.put(exceptionType, refinedStore); - refined = true; } - return refined ? result.withExceptionalStores(newExceptionalStores) : result; + return result.withExceptionalStores(newExceptionalStores); } /** diff --git a/checker/tests/nullness/ReceiverRefinementInCatch.java b/checker/tests/nullness/ReceiverRefinementInCatch.java index 16946e8425f3..592fd7a35e73 100644 --- a/checker/tests/nullness/ReceiverRefinementInCatch.java +++ b/checker/tests/nullness/ReceiverRefinementInCatch.java @@ -103,6 +103,29 @@ void errorHandler(@Nullable Object o) { } } + // As for a call in source code, the synthetic iterator() call of an enhanced for loop throws the + // NullPointerException for a null iterable at its method lookup. Every other exception from + // the loop's iterator protocol comes from an invoked method, so the iterable is non-null in a + // handler that cannot catch a NullPointerException. + void enhancedForUncheckedExceptionHandler(@Nullable Iterable items) { + try { + // :: error: (iterating.over.nullable) + for (Object x : items) {} + } catch (IllegalArgumentException e) { + items.toString(); + } + } + + void enhancedForNullPointerExceptionHandler(@Nullable Iterable items) { + try { + // :: error: (iterating.over.nullable) + for (Object x : items) {} + } catch (NullPointerException e) { + // :: error: (dereference.of.nullable) + items.toString(); + } + } + void afterNormalCompletion(@Nullable Object o) { // :: error: (dereference.of.nullable) o.toString(); diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index c7700b998eb4..2cb9c3c20a92 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -1879,7 +1879,10 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { MethodAccessNode iteratorAccessNode = new MethodAccessNode(iteratorSelect, expressionNode); iteratorAccessNode.setInSource(false); - extendWithNode(iteratorAccessNode); + // As for an invocation in source code, the method access throws the NullPointerException + // for a null receiver, so every exceptional successor of the invocation has a non-null + // receiver. The same holds for hasNext() and next() below. + extendWithNode(iteratorAccessNode, mayBeNull(expressionNode)); MethodInvocationNode iteratorCallNode = new MethodInvocationNode( iteratorCall, iteratorAccessNode, Collections.emptyList(), getCurrentPath()); @@ -1904,7 +1907,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { MethodAccessNode hasNextAccessNode = new MethodAccessNode(hasNextSelect, iteratorReceiverNode); hasNextAccessNode.setInSource(false); - extendWithNode(hasNextAccessNode); + extendWithNode(hasNextAccessNode, mayBeNull(iteratorReceiverNode)); MethodInvocationTree hasNextCall = treeBuilder.buildMethodInvocation(hasNextSelect); handleArtificialTree(hasNextCall); @@ -1932,7 +1935,7 @@ public Node visitEnhancedForLoop(EnhancedForLoopTree tree, Void p) { MethodAccessNode nextAccessNode = new MethodAccessNode(nextSelect, iteratorReceiverNode2); nextAccessNode.setInSource(false); - extendWithNode(nextAccessNode); + extendWithNode(nextAccessNode, mayBeNull(iteratorReceiverNode2)); MethodInvocationTree nextCall = treeBuilder.buildMethodInvocation(nextSelect); handleArtificialTree(nextCall); @@ -3821,7 +3824,11 @@ protected void treatMethodAsAssert( * @param condition the boolean expression node for the argument that the method tests * @param nullReceiverThrows true if the call has a receiver that may be null. Then, on the path * on which the assertion fails, the call may throw a {@code NullPointerException} instead of - * invoking the method. (On the other path, the call's method access throws it.) + * invoking the method. (On the other path, the call's method access throws it.) Like the + * {@code AssertionError} on that path, this {@code NullPointerException} is thrown before any + * argument that follows the condition is evaluated, though at run time the call evaluates + * every argument first. Modeling that would require evaluating the later arguments on both + * paths, or branching after them, which would lose the refinement from the condition. */ private void treatMethodAsAssert( MethodInvocationTree tree, From 4fb9f94347e3987d33c2c2a4de9f5b10de8f6303 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 23:17:48 -0800 Subject: [PATCH 95/98] Resolve implicit close() and other no-argument methods through type-variable and intersection bounds; account for an assert detail's string conversion; remove a redundant @Nullable --- .../checker/nullness/NullnessTransfer.java | 39 ++++++++++- .../ReceiverReassignedByImplicitCall.java | 65 +++++++++++++++++++ 2 files changed, 101 insertions(+), 3 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 62e5a411cc99..2ac2d3290fd9 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -1,6 +1,7 @@ package org.checkerframework.checker.nullness; import com.sun.source.tree.AnnotationTree; +import com.sun.source.tree.AssertTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ClassTree; @@ -27,8 +28,10 @@ import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; +import javax.lang.model.type.IntersectionType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; +import javax.lang.model.type.TypeVariable; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import org.checkerframework.checker.initialization.InitializationTransfer; @@ -468,7 +471,7 @@ public TransferResult visitMethodInvocation( // The exceptional successors of the invocation get the store before the invocation, which // super.visitMethodInvocation modifies in place. So, copy it first. A `this` or `super` // receiver is always non-null, so its exceptional successors need no refinement. - @Nullable NullnessStore storeBeforeInvocation = + NullnessStore storeBeforeInvocation = refineReceiver && n.getBlock() instanceof ExceptionBlock && !(receiver instanceof ThisNode) @@ -601,8 +604,9 @@ private TransferResult refineReceiverOnExceptional * side-effect-free. * *

Matching a record pattern, as in {@code o instanceof R(int i)}, implicitly invokes the - * record's component accessors. Likewise, string conversion implicitly invokes {@code - * toString()}, a try-with-resources statement implicitly invokes {@code close()}, and an enhanced + * record's component accessors. Likewise, string conversion (including that of the detail + * message of a failing {@code assert} statement) implicitly invokes {@code toString()}, a + * try-with-resources statement implicitly invokes {@code close()}, and an enhanced * {@code for} loop over an {@code Iterable} implicitly invokes {@code iterator()}, {@code * hasNext()}, and {@code next()}. (An argument can contain a statement within a switch * expression.) This method handles these implicit invocations as it handles explicit method @@ -699,6 +703,16 @@ && recordPatternMayHaveSideEffect(tree)) { return super.scan(tree, p); } + // A failing assert statement converts its detail message to a string, in the + // AssertionError constructor. That implicitly invokes toString() on a detail that is + // not a String or a primitive. + @Override + public Boolean visitAssert(AssertTree tree, Void p) { + ExpressionTree detail = tree.getDetail(); + return (detail != null && stringConversionMayHaveSideEffect(detail)) + || super.visitAssert(tree, p); + } + // A try-with-resources statement implicitly invokes close() on each resource. @Override public Boolean visitTry(TryTree tree, Void p) { @@ -870,11 +884,30 @@ private TypeMirror returnTypeAsMemberOf(TypeMirror type, ExecutableElement metho * of them, which is conservative. Returns an empty list if the erasure has no type * element, as for an array type. * + *

For a type variable, uses its upper bound. For an intersection type, such as the + * bound of {@code T extends Base & PureClose}, returns the methods of every component + * (rather than only those of the erasure, which is the first component), which is + * conservative. + * * @param type a type * @param name a method name * @return the most specific no-argument methods named {@code name} in {@code type} */ private List noArgMethods(TypeMirror type, String name) { + if (type.getKind() == TypeKind.TYPEVAR) { + return noArgMethods(((TypeVariable) type).getUpperBound(), name); + } + if (type.getKind() == TypeKind.INTERSECTION) { + List result = new ArrayList<>(); + for (TypeMirror bound : ((IntersectionType) type).getBounds()) { + for (ExecutableElement m : noArgMethods(bound, name)) { + if (!result.contains(m)) { + result.add(m); + } + } + } + return result; + } TypeElement typeElement = TypesUtils.getTypeElement(analysis.getTypes().erasure(type)); if (typeElement == null) { return List.of(); diff --git a/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java index 17a32d0c36c1..6e2681e57235 100644 --- a/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java +++ b/checker/tests/nullness/java17/ReceiverReassignedByImplicitCall.java @@ -96,6 +96,71 @@ void resourceCloseIsPureDespitePrivateSuperclassClose(int tag) { f.toString(); } + class ResourceBaseWithoutClose {} + + interface PureCloseable extends AutoCloseable { + @Override + @SideEffectFree + void close(); + } + + interface UncheckedCloseable extends AutoCloseable { + @Override + void close(); + } + + // The erasure of T is ResourceBaseWithoutClose, which has no close() method. The close() that + // try-with-resources invokes is PureCloseable.close(). + void intersectionResourceCloseIsPure( + int tag, T resource) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + try (resource) {} + yield 0; + } + }); + f.toString(); + } + + + void intersectionResourceCloseMightClearReceiver(int tag, T resource) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + try (resource) {} + yield 0; + } + }); + // :: error: (dereference.of.nullable) + f.toString(); + } + + class SefToString { + @Override + @SideEffectFree + public String toString() { + return ""; + } + } + + // A failing assert statement converts its detail message to a string. A String detail and a + // detail with a side-effect-free toString() do not reassign f. + void assertDetailIsPure(int tag, SefToString detail) { + // :: error: (dereference.of.nullable) + f.take( + switch (tag) { + default -> { + assert tag > 0 : "message"; + assert tag > 1 : detail; + yield 0; + } + }); + f.toString(); + } + // A try statement without resources invokes no method. void tryWithoutResources(int tag) { // :: error: (dereference.of.nullable) From faab83804352559a8d2d25b6bb2895236ddcc6df Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 23:18:58 -0800 Subject: [PATCH 96/98] CFGConstruction test: check that each rethrow reaches the catch block for its type --- .../java/cfgconstruction/CFGConstruction.java | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java index 5ec34ba9b8d6..9687d94d768a 100644 --- a/dataflow/src/test/java/cfgconstruction/CFGConstruction.java +++ b/dataflow/src/test/java/cfgconstruction/CFGConstruction.java @@ -7,10 +7,13 @@ import java.util.Map; import java.util.Set; import javax.lang.model.type.TypeMirror; +import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.cfg.ControlFlowGraph; import org.checkerframework.dataflow.cfg.block.Block; import org.checkerframework.dataflow.cfg.block.ExceptionBlock; +import org.checkerframework.dataflow.cfg.node.CatchMarkerNode; import org.checkerframework.dataflow.cfg.node.MarkerNode; +import org.checkerframework.dataflow.cfg.node.Node; import org.checkerframework.dataflow.cfg.visualize.CFGVisualizeLauncher; public class CFGConstruction { @@ -81,7 +84,7 @@ private static List exceptionalCopyEnds(ControlFlowGraph cfg) { /** * Checks that the given blocks together rethrow exactly IOException, RuntimeException, and Error, - * each to a different catch block. + * each to a different catch block, namely the one that catches that type. * * @param copyEnds the blocks that end the exceptional finally-block copies of an original finally * block @@ -115,5 +118,34 @@ private static void checkRethrowsToDistinctHandlers(List copyEnd throw new Error("Expected rethrows to catch blocks, found " + handler); } } + for (ExceptionBlock copyEnd : copyEnds) { + for (Map.Entry> entry : + copyEnd.getExceptionalSuccessors().entrySet()) { + String typeName = entry.getKey().toString(); + Block handler = entry.getValue().iterator().next(); + String catchTypeName = catchTypeName(handler); + if (!typeName.equals(catchTypeName)) { + throw new Error( + "Expected rethrow of " + typeName + " to its catch block, found " + handler); + } + } + } + } + + /** + * Returns the name of the type caught by the catch block that starts with the given block. + * + * @param handler a block + * @return the name of the type caught by the catch block that starts with {@code handler}, or + * null if {@code handler} does not start a catch block + */ + private static @Nullable String catchTypeName(Block handler) { + List nodes = handler.getNodes(); + if (!nodes.isEmpty() + && nodes.get(0) instanceof CatchMarkerNode marker + && marker.getMessage().startsWith("start of catch block for ")) { + return marker.getCatchType().toString(); + } + return null; } } From ced9c96374b763da43c09414c6cd14238bdb4381 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 23:44:56 -0800 Subject: [PATCH 97/98] Reformat --- .../dataflow/cfg/builder/CFGTranslationPhaseOne.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java index 9a304d3cb321..9329db7f71dc 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/cfg/builder/CFGTranslationPhaseOne.java @@ -2992,7 +2992,8 @@ private List closeThrownTypes(Tree resourceDeclarationTree // clause. } } - // A close method of a class overrides the close methods of the interfaces, and its throws clause + // A close method of a class overrides the close methods of the interfaces, and its throws + // clause // must be compatible with theirs, so its throws clause is the effective one. Only a method of // an interface might be one of several inherited declarations. if (!closeMethod.getEnclosingElement().getKind().isInterface()) { From ad0bde38f75f19dfa92cfedad239c00d54861656 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 23:51:29 -0800 Subject: [PATCH 98/98] Reformat --- .../checker/nullness/NullnessTransfer.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 2ac2d3290fd9..6e14c6625458 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -604,13 +604,12 @@ private TransferResult refineReceiverOnExceptional * side-effect-free. * *

Matching a record pattern, as in {@code o instanceof R(int i)}, implicitly invokes the - * record's component accessors. Likewise, string conversion (including that of the detail - * message of a failing {@code assert} statement) implicitly invokes {@code toString()}, a - * try-with-resources statement implicitly invokes {@code close()}, and an enhanced - * {@code for} loop over an {@code Iterable} implicitly invokes {@code iterator()}, {@code - * hasNext()}, and {@code next()}. (An argument can contain a statement within a switch - * expression.) This method handles these implicit invocations as it handles explicit method - * invocations. + * record's component accessors. Likewise, string conversion (including that of the detail message + * of a failing {@code assert} statement) implicitly invokes {@code toString()}, a + * try-with-resources statement implicitly invokes {@code close()}, and an enhanced {@code for} + * loop over an {@code Iterable} implicitly invokes {@code iterator()}, {@code hasNext()}, and + * {@code next()}. (An argument can contain a statement within a switch expression.) This method + * handles these implicit invocations as it handles explicit method invocations. * *

This method does not examine the bodies of lambda expressions and anonymous classes in the * arguments. Evaluating the arguments executes such a body only through a method or constructor