Loosening requirements for super() invocation

Archie Cobbs archie.cobbs at gmail.com
Wed Nov 9 15:54:45 UTC 2022


On Tue, Nov 8, 2022 at 3:00 PM Brian Goetz <brian.goetz at oracle.com> wrote:

>
> The goal is to close off all routes by which 'this' could end up being
> passed to code in any subclass.
>
> any other class outside this compilation unit: subclass, superclass,
> random class.  This is sometimes called "alien" code -- code this class
> does not control.  (Note that inner classes in the current class are OK;
> it's under this classes control.)
>

Yes I think we're saying the same thing - passing 'this' to any "alien"
code is a leak.

I'm just pointing out that the damage doesn't actually occur until if/when
the 'this' is actually used to access state in a subclass. But that's just
a technical point and doesn't ultimately change the kinds of expressions we
have to watch out for.


> A 'this' escape is when, in a non-final class MyClass constructor, after
> a super() call, a reference to the 'this' instance is used, explicitly or
> implicitly, in any expression that (as far as the compiler can tell) might
> possibly:
>
>    1. Invoke a non-static method declared in any strict supertype of
>    MyClass
>
>
> Declared outside the compilation unit of MyClass
>

Agreed... that formulation is simpler. But of course it would need a caveat
for subclasses within the same compilation unit, e.g.:

public class Example {

    public static abstract class A {

        public A() {
            System.out.println(this.foo());
        }

        public abstract int foo();
    }

    public static class B extends A {

        private final int x;

        public B(int x) {
            this.x = x;
        }

        public int foo() {
            return this.x;
        }
    }

    public static void main(String[] args) {
        new B(123);     // prints "0"
    }
}

>
> Here's a more advanced case that would require more sophisticated data
> flow analysis, but might not be so bad:
>
> public class X {
>     public X() { foo(this); }
>
>     private static void foo(X x) {  }
> }
>
> Here, you pass `this` to foo(), but it doesn't do anything bad with it.
>

Yeah, that would be harder to track but feasible. I'd need to think about
how to do that properly.

However I should be able to come up with an initial prototype for the basic
'this' escape warning without too much work. I'll email when I have
something.

Thanks,
-Archie

-- 
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20221109/46ea583c/attachment-0001.htm>


More information about the amber-dev mailing list