8022718: Runtime accessibility checking: protected class, if extended, should be accessible from another package
authordrchase
Wed, 16 Oct 2013 17:55:49 -0400
changeset 20872 8e486b70dff8
parent 20871 b5fa714232e7
child 20873 e91d5b1cb8e6
child 20875 350103ea501d
8022718: Runtime accessibility checking: protected class, if extended, should be accessible from another package Summary: Modify accessibility check; it was muddled about Java vs JVM protection terminology. Reviewed-by: jrose
jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java
jdk/src/share/classes/sun/invoke/util/VerifyAccess.java
jdk/src/share/classes/sun/reflect/Reflection.java
jdk/test/java/lang/invoke/accessProtectedSuper/BogoLoader.java
jdk/test/java/lang/invoke/accessProtectedSuper/MethodInvoker.java
jdk/test/java/lang/invoke/accessProtectedSuper/Test.java
jdk/test/java/lang/invoke/accessProtectedSuper/anotherpkg/MethodSupplierOuter.java
--- a/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Thu Oct 17 20:56:07 2013 +0800
+++ b/jdk/src/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Wed Oct 16 17:55:49 2013 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -609,6 +609,7 @@
             cls = cls.getComponentType();
         if (cls.isPrimitive())
             return true;  // int[].class, for example
+        // could use VerifyAccess.isClassAccessible but the following is a safe approximation
         if (cls.getClassLoader() != Object.class.getClassLoader())
             return false;
         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
--- a/jdk/src/share/classes/sun/invoke/util/VerifyAccess.java	Thu Oct 17 20:56:07 2013 +0800
+++ b/jdk/src/share/classes/sun/invoke/util/VerifyAccess.java	Wed Oct 16 17:55:49 2013 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.lang.reflect.Modifier;
 import static java.lang.reflect.Modifier.*;
+import sun.reflect.Reflection;
 
 /**
  * This class centralizes information about the JVM's linkage access control.
@@ -140,7 +141,17 @@
     }
 
     static boolean isPublicSuperClass(Class<?> defc, Class<?> lookupClass) {
-        return isPublic(defc.getModifiers()) && defc.isAssignableFrom(lookupClass);
+        return isPublic(getClassModifiers(defc)) && defc.isAssignableFrom(lookupClass);
+    }
+
+    static int getClassModifiers(Class<?> c) {
+        // This would return the mask stored by javac for the source-level modifiers.
+        //   return c.getModifiers();
+        // But what we need for JVM access checks are the actual bits from the class header.
+        // ...But arrays and primitives are synthesized with their own odd flags:
+        if (c.isArray() || c.isPrimitive())
+            return c.getModifiers();
+        return Reflection.getClassAccessFlags(c);
     }
 
     /**
@@ -159,7 +170,7 @@
         if (allowedModes == 0)  return false;
         assert((allowedModes & PUBLIC) != 0 &&
                (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED)) == 0);
-        int mods = refc.getModifiers();
+        int mods = getClassModifiers(refc);
         if (isPublic(mods))
             return true;
         if ((allowedModes & PACKAGE_ALLOWED) != 0 &&
--- a/jdk/src/share/classes/sun/reflect/Reflection.java	Thu Oct 17 20:56:07 2013 +0800
+++ b/jdk/src/share/classes/sun/reflect/Reflection.java	Wed Oct 16 17:55:49 2013 -0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -65,7 +65,7 @@
         to compatibility reasons; see 4471811. Only the values of the
         low 13 bits (i.e., a mask of 0x1FFF) are guaranteed to be
         valid. */
-    private static native int getClassAccessFlags(Class<?> c);
+    public static native int getClassAccessFlags(Class<?> c);
 
     /** A quick "fast-path" check to try to avoid getCallerClass()
         calls. */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/accessProtectedSuper/BogoLoader.java	Wed Oct 16 17:55:49 2013 -0400
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Set;
+import java.util.Vector;
+import jdk.internal.org.objectweb.asm.*;
+// Compile with -XDignore.symbol.file=true
+
+public class BogoLoader extends ClassLoader {
+
+    static interface VisitorMaker {
+    ClassVisitor make(ClassVisitor visitor);
+    }
+
+
+    /**
+     * Use this property to verify that the desired classloading is happening.
+     */
+    private final boolean verbose = Boolean.getBoolean("bogoloader.verbose");
+    /**
+     * Use this property to disable replacement for testing purposes.
+     */
+    private final boolean noReplace = Boolean.getBoolean("bogoloader.noreplace");
+
+    /**
+     * Set of class names that should be loaded with this loader.
+     * Others are loaded with the system class loader, except for those
+     * that are transformed.
+     */
+    private Set<String> nonSystem;
+
+    /**
+     * Map from class names to a bytecode transformer factory.
+     */
+    private Map<String, VisitorMaker> replaced;
+
+    /**
+     * Keep track (not terribly efficiently) of which classes have already
+     * been loaded by this class loader.
+     */
+    private final Vector<String> history = new Vector<String>();
+
+    private boolean useSystemLoader(String name) {
+        return ! nonSystem.contains(name) && ! replaced.containsKey(name);
+    }
+
+    public BogoLoader(Set<String> non_system, Map<String, VisitorMaker> replaced) {
+        super(Thread.currentThread().getContextClassLoader());
+        this.nonSystem = non_system;
+        this.replaced = replaced;
+    }
+
+    private byte[] readResource(String className) throws IOException {
+        return readResource(className, "class");
+    }
+
+    private byte[] readResource(String className, String suffix) throws IOException {
+        // Note to the unwary -- "/" works on Windows, leave it alone.
+        String fileName = className.replace('.', '/') + "." + suffix;
+        InputStream origStream = getResourceAsStream(fileName);
+        if (origStream == null) {
+            throw new IOException("Resource not found : " + fileName);
+        }
+        BufferedInputStream stream = new java.io.BufferedInputStream(origStream);
+        byte[] data = new byte[stream.available()];
+        int how_many = stream.read(data);
+        // Really ought to deal with the corner cases of stream.available()
+        return data;
+    }
+
+    protected byte[] getClass(String name) throws ClassNotFoundException,
+    IOException {
+        return readResource(name, "class");
+    }
+
+    /**
+     * Loads the named class from the system class loader unless
+     * the name appears in either replaced or nonSystem.
+     * nonSystem classes are loaded into this classloader,
+     * and replaced classes get their content from the specified array
+     * of bytes (and are also loaded into this classloader).
+     */
+    protected Class<?> loadClass(String name, boolean resolve)
+            throws ClassNotFoundException {
+        Class<?> clazz;
+
+        if (history.contains(name)) {
+            Class<?> c = this.findLoadedClass(name);
+            return c;
+        }
+        if (useSystemLoader(name)) {
+            clazz = findSystemClass(name);
+            if (verbose) System.err.println("Loading system class " + name);
+        } else {
+            history.add(name);
+            try {
+                if (verbose) {
+                    System.err.println("Loading classloader class " + name);
+                }
+                byte[] classData = getClass(name);;
+                boolean expanded = false;
+                if (!noReplace && replaced.containsKey(name)) {
+                    if (verbose) {
+                        System.err.println("Replacing class " + name);
+                    }
+                    ClassReader cr = new ClassReader(classData);
+                    ClassWriter cw = new ClassWriter(0);
+                    VisitorMaker vm = replaced.get(name);
+                    cr.accept(vm.make(cw), 0);
+                    classData = cw.toByteArray();
+                }
+                clazz = defineClass(name, classData, 0, classData.length);
+            } catch (java.io.EOFException ioe) {
+                throw new ClassNotFoundException(
+                        "IO Exception in reading class : " + name + " ", ioe);
+            } catch (ClassFormatError ioe) {
+                throw new ClassNotFoundException(
+                        "ClassFormatError in reading class file: ", ioe);
+            } catch (IOException ioe) {
+                throw new ClassNotFoundException(
+                        "IO Exception in reading class file: ", ioe);
+            }
+        }
+        if (clazz == null) {
+            throw new ClassNotFoundException(name);
+        }
+        if (resolve) {
+            resolveClass(clazz);
+        }
+        return clazz;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/accessProtectedSuper/MethodInvoker.java	Wed Oct 16 17:55:49 2013 -0400
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+import anotherpkg.MethodSupplierOuter;
+
+public class MethodInvoker extends MethodSupplierOuter.MethodSupplier {
+    public static void invoke() throws Exception {
+        MethodInvoker ms = new MethodInvoker();
+        ms.m();
+        ms.myfi().invokeMethodReference();
+        MyFunctionalInterface fi = ms::m; // Should not fail with modified bytecodes
+        fi.invokeMethodReference();
+    }
+
+    MyFunctionalInterface myfi() {
+        MyFunctionalInterface fi = this::m; // Should not fail with modified bytecodes
+        return fi;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/accessProtectedSuper/Test.java	Wed Oct 16 17:55:49 2013 -0400
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 8022718
+ * @summary Runtime accessibility checking: protected class, if extended, should be accessible from another package
+ *
+ * @compile -XDignore.symbol.file BogoLoader.java MethodInvoker.java Test.java anotherpkg/MethodSupplierOuter.java
+ * @run main/othervm Test
+ */
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.HashSet;
+import jdk.internal.org.objectweb.asm.ClassWriter;
+import jdk.internal.org.objectweb.asm.MethodVisitor;
+import jdk.internal.org.objectweb.asm.ClassVisitor;
+import jdk.internal.org.objectweb.asm.Opcodes;
+
+interface MyFunctionalInterface {
+
+    void invokeMethodReference();
+}
+
+class MakeProtected implements BogoLoader.VisitorMaker, Opcodes {
+
+    final boolean whenVisitInner;
+
+    MakeProtected(boolean when_visit_inner) {
+        super();
+        whenVisitInner = when_visit_inner;
+    }
+
+    public ClassVisitor make(ClassVisitor cv) {
+        return new ClassVisitor(Opcodes.ASM5, cv) {
+
+            @Override
+            public void visitInnerClass(String name, String outerName,
+                    String innerName, int access) {
+                if (whenVisitInner) {
+                    int access_ = (ACC_PROTECTED | access) & ~(ACC_PRIVATE | ACC_PUBLIC);
+                    System.out.println("visitInnerClass: name = " + name
+                            + ", outerName = " + outerName
+                            + ", innerName = " + innerName
+                            + ", access original = 0x" + Integer.toHexString(access)
+                            + ", access modified to 0x" + Integer.toHexString(access_));
+                    access = access_;
+                }
+                super.visitInnerClass(name, outerName, innerName, access);
+            }
+        };
+    }
+};
+
+public class Test {
+
+    public static void main(String argv[]) throws Exception, Throwable {
+        BogoLoader.VisitorMaker makeProtectedNop = new MakeProtected(false);
+        BogoLoader.VisitorMaker makeProtectedMod = new MakeProtected(true);
+
+        int errors = 0;
+        errors += tryModifiedInvocation(makeProtectedNop);
+        errors += tryModifiedInvocation(makeProtectedMod);
+
+        if (errors > 0) {
+            throw new Error("FAIL; there were errors");
+        }
+    }
+
+    private static int tryModifiedInvocation(BogoLoader.VisitorMaker makeProtected)
+            throws Throwable, ClassNotFoundException {
+        HashMap<String, BogoLoader.VisitorMaker> replace
+                = new HashMap<String, BogoLoader.VisitorMaker>();
+        replace.put("anotherpkg.MethodSupplierOuter$MethodSupplier", makeProtected);
+        HashSet<String> in_bogus = new HashSet<String>();
+        in_bogus.add("MethodInvoker");
+        in_bogus.add("MyFunctionalInterface");
+        in_bogus.add("anotherpkg.MethodSupplierOuter"); // seems to be never loaded
+        in_bogus.add("anotherpkg.MethodSupplierOuter$MethodSupplier");
+
+        BogoLoader bl = new BogoLoader(in_bogus, replace);
+        try {
+            Class<?> isw = bl.loadClass("MethodInvoker");
+            Method meth = isw.getMethod("invoke");
+            Object result = meth.invoke(null);
+        } catch (Throwable th) {
+            System.out.flush();
+            Thread.sleep(250); // Let Netbeans get its I/O sorted out.
+            th.printStackTrace();
+            System.err.flush();
+            Thread.sleep(250); // Let Netbeans get its I/O sorted out.
+            return 1;
+        }
+        return 0;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/accessProtectedSuper/anotherpkg/MethodSupplierOuter.java	Wed Oct 16 17:55:49 2013 -0400
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+package anotherpkg;
+
+public class MethodSupplierOuter {
+    // MethodSupplier is "public" for javac compilation, modified to "protected" for test.
+    public static class MethodSupplier {
+        public void m() {
+            System.out.println("good");
+        }
+    }
+}