rt/emul/compact/src/main/java/sun/invoke/util/VerifyAccess.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Aug 2014 06:13:36 +0200
branchjdk8
changeset 1651 5c990ed353e9
parent 1646 c880a8a8803b
permissions -rw-r--r--
Almost compiled java.lang.invoke, except the parts that deal with Asm bytecode generator
     1 /*
     2  * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 package sun.invoke.util;
    27 
    28 import java.lang.reflect.Modifier;
    29 import static java.lang.reflect.Modifier.*;
    30 
    31 /**
    32  * This class centralizes information about the JVM's linkage access control.
    33  * @author jrose
    34  */
    35 public class VerifyAccess {
    36 
    37     private VerifyAccess() { }  // cannot instantiate
    38 
    39     private static final int PACKAGE_ONLY = 0;
    40     private static final int PACKAGE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.PACKAGE;
    41     private static final int PROTECTED_OR_PACKAGE_ALLOWED = (PACKAGE_ALLOWED|PROTECTED);
    42     private static final int ALL_ACCESS_MODES = (PUBLIC|PRIVATE|PROTECTED|PACKAGE_ONLY);
    43     private static final boolean ALLOW_NESTMATE_ACCESS = false;
    44 
    45     /**
    46      * Evaluate the JVM linkage rules for access to the given method
    47      * on behalf of a caller class which proposes to perform the access.
    48      * Return true if the caller class has privileges to invoke a method
    49      * or access a field with the given properties.
    50      * This requires an accessibility check of the referencing class,
    51      * plus an accessibility check of the member within the class,
    52      * which depends on the member's modifier flags.
    53      * <p>
    54      * The relevant properties include the defining class ({@code defc})
    55      * of the member, and its modifier flags ({@code mods}).
    56      * Also relevant is the class used to make the initial symbolic reference
    57      * to the member ({@code refc}).  If this latter class is not distinguished,
    58      * the defining class should be passed for both arguments ({@code defc == refc}).
    59      * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
    60      * A field or method R is accessible to a class or interface D if
    61      * and only if any of the following conditions is true:<ul>
    62      * <li>R is public.
    63      * <li>R is protected and is declared in a class C, and D is either
    64      *     a subclass of C or C itself.  Furthermore, if R is not
    65      *     static, then the symbolic reference to R must contain a
    66      *     symbolic reference to a class T, such that T is either a
    67      *     subclass of D, a superclass of D or D itself.
    68      * <li>R is either protected or has default access (that is,
    69      *     neither public nor protected nor private), and is declared
    70      *     by a class in the same runtime package as D.
    71      * <li>R is private and is declared in D.
    72      * </ul>
    73      * This discussion of access control omits a related restriction
    74      * on the target of a protected field access or method invocation
    75      * (the target must be of class D or a subtype of D). That
    76      * requirement is checked as part of the verification process
    77      * (5.4.1); it is not part of link-time access control.
    78      * @param refc the class used in the symbolic reference to the proposed member
    79      * @param defc the class in which the proposed member is actually defined
    80      * @param mods modifier flags for the proposed member
    81      * @param lookupClass the class for which the access check is being made
    82      * @return true iff the the accessing class can access such a member
    83      */
    84     public static boolean isMemberAccessible(Class<?> refc,  // symbolic ref class
    85                                              Class<?> defc,  // actual def class
    86                                              int      mods,  // actual member mods
    87                                              Class<?> lookupClass,
    88                                              int      allowedModes) {
    89         if (allowedModes == 0)  return false;
    90         assert((allowedModes & PUBLIC) != 0 &&
    91                (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED)) == 0);
    92         // The symbolic reference class (refc) must always be fully verified.
    93         if (!isClassAccessible(refc, lookupClass, allowedModes)) {
    94             return false;
    95         }
    96         // Usually refc and defc are the same, but verify defc also in case they differ.
    97         if (defc == lookupClass &&
    98             (allowedModes & PRIVATE) != 0)
    99             return true;        // easy check; all self-access is OK
   100         switch (mods & ALL_ACCESS_MODES) {
   101         case PUBLIC:
   102             return true;  // already checked above
   103         case PROTECTED:
   104             if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
   105                 isSamePackage(defc, lookupClass))
   106                 return true;
   107             if ((allowedModes & PROTECTED) == 0)
   108                 return false;
   109             if ((mods & STATIC) != 0 &&
   110                 !isRelatedClass(refc, lookupClass))
   111                 return false;
   112             if ((allowedModes & PROTECTED) != 0 &&
   113                 isSuperClass(defc, lookupClass))
   114                 return true;
   115             return false;
   116         case PACKAGE_ONLY:  // That is, zero.  Unmarked member is package-only access.
   117             return ((allowedModes & PACKAGE_ALLOWED) != 0 &&
   118                     isSamePackage(defc, lookupClass));
   119         case PRIVATE:
   120             // Loosened rules for privates follows access rules for inner classes.
   121             return (ALLOW_NESTMATE_ACCESS &&
   122                     (allowedModes & PRIVATE) != 0 &&
   123                     isSamePackageMember(defc, lookupClass));
   124         default:
   125             throw new IllegalArgumentException("bad modifiers: "+Modifier.toString(mods));
   126         }
   127     }
   128 
   129     static boolean isRelatedClass(Class<?> refc, Class<?> lookupClass) {
   130         return (refc == lookupClass ||
   131                 refc.isAssignableFrom(lookupClass) ||
   132                 lookupClass.isAssignableFrom(refc));
   133     }
   134 
   135     static boolean isSuperClass(Class<?> defc, Class<?> lookupClass) {
   136         return defc.isAssignableFrom(lookupClass);
   137     }
   138 
   139     static int getClassModifiers(Class<?> c) {
   140         // This would return the mask stored by javac for the source-level modifiers.
   141         //   return c.getModifiers();
   142         // But what we need for JVM access checks are the actual bits from the class header.
   143         // ...But arrays and primitives are synthesized with their own odd flags:
   144         if (c.isArray() || c.isPrimitive())
   145             return c.getModifiers();
   146         return c.getModifiers();
   147 //        return Reflection.getClassAccessFlags(c);
   148     }
   149 
   150     /**
   151      * Evaluate the JVM linkage rules for access to the given class on behalf of caller.
   152      * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
   153      * A class or interface C is accessible to a class or interface D
   154      * if and only if either of the following conditions are true:<ul>
   155      * <li>C is public.
   156      * <li>C and D are members of the same runtime package.
   157      * </ul>
   158      * @param refc the symbolic reference class to which access is being checked (C)
   159      * @param lookupClass the class performing the lookup (D)
   160      */
   161     public static boolean isClassAccessible(Class<?> refc, Class<?> lookupClass,
   162                                             int allowedModes) {
   163         if (allowedModes == 0)  return false;
   164         assert((allowedModes & PUBLIC) != 0 &&
   165                (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED)) == 0);
   166         int mods = getClassModifiers(refc);
   167         if (isPublic(mods))
   168             return true;
   169         if ((allowedModes & PACKAGE_ALLOWED) != 0 &&
   170             isSamePackage(lookupClass, refc))
   171             return true;
   172         return false;
   173     }
   174 
   175     /**
   176      * Decide if the given method type, attributed to a member or symbolic
   177      * reference of a given reference class, is really visible to that class.
   178      * @param type the supposed type of a member or symbolic reference of refc
   179      * @param refc the class attempting to make the reference
   180      */
   181     public static boolean isTypeVisible(Class<?> type, Class<?> refc) {
   182         if (type == refc)  return true;  // easy check
   183         while (type.isArray())  type = type.getComponentType();
   184         if (type.isPrimitive() || type == Object.class)  return true;
   185         ClassLoader parent = type.getClassLoader();
   186         if (parent == null)  return true;
   187         ClassLoader child  = refc.getClassLoader();
   188         if (child == null)  return false;
   189         if (parent == child || loadersAreRelated(parent, child, true))
   190             return true;
   191         // Do it the hard way:  Look up the type name from the refc loader.
   192         try {
   193             Class<?> res = child.loadClass(type.getName());
   194             return (type == res);
   195         } catch (ClassNotFoundException ex) {
   196             return false;
   197         }
   198     }
   199 
   200     /**
   201      * Decide if the given method type, attributed to a member or symbolic
   202      * reference of a given reference class, is really visible to that class.
   203      * @param type the supposed type of a member or symbolic reference of refc
   204      * @param refc the class attempting to make the reference
   205      */
   206     public static boolean isTypeVisible(java.lang.invoke.MethodType type, Class<?> refc) {
   207         for (int n = -1, max = type.parameterCount(); n < max; n++) {
   208             Class<?> ptype = (n < 0 ? type.returnType() : type.parameterType(n));
   209             if (!isTypeVisible(ptype, refc))
   210                 return false;
   211         }
   212         return true;
   213     }
   214 
   215     /**
   216      * Test if two classes have the same class loader and package qualifier.
   217      * @param class1 a class
   218      * @param class2 another class
   219      * @return whether they are in the same package
   220      */
   221     public static boolean isSamePackage(Class<?> class1, Class<?> class2) {
   222         assert(!class1.isArray() && !class2.isArray());
   223         if (class1 == class2)
   224             return true;
   225         if (class1.getClassLoader() != class2.getClassLoader())
   226             return false;
   227         String name1 = class1.getName(), name2 = class2.getName();
   228         int dot = name1.lastIndexOf('.');
   229         if (dot != name2.lastIndexOf('.'))
   230             return false;
   231         for (int i = 0; i < dot; i++) {
   232             if (name1.charAt(i) != name2.charAt(i))
   233                 return false;
   234         }
   235         return true;
   236     }
   237 
   238     /** Return the package name for this class.
   239      */
   240     public static String getPackageName(Class<?> cls) {
   241         assert(!cls.isArray());
   242         String name = cls.getName();
   243         int dot = name.lastIndexOf('.');
   244         if (dot < 0)  return "";
   245         return name.substring(0, dot);
   246     }
   247 
   248     /**
   249      * Test if two classes are defined as part of the same package member (top-level class).
   250      * If this is true, they can share private access with each other.
   251      * @param class1 a class
   252      * @param class2 another class
   253      * @return whether they are identical or nested together
   254      */
   255     public static boolean isSamePackageMember(Class<?> class1, Class<?> class2) {
   256         if (class1 == class2)
   257             return true;
   258         if (!isSamePackage(class1, class2))
   259             return false;
   260         if (getOutermostEnclosingClass(class1) != getOutermostEnclosingClass(class2))
   261             return false;
   262         return true;
   263     }
   264 
   265     private static Class<?> getOutermostEnclosingClass(Class<?> c) {
   266         throw new IllegalStateException("Needed?");
   267 //        Class<?> pkgmem = c;
   268 //        for (Class<?> enc = c; (enc = enc.getEnclosingClass()) != null; )
   269 //            pkgmem = enc;
   270 //        return pkgmem;
   271     }
   272 
   273     private static boolean loadersAreRelated(ClassLoader loader1, ClassLoader loader2,
   274                                              boolean loader1MustBeParent) {
   275         if (loader1 == loader2 || loader1 == null
   276                 || (loader2 == null && !loader1MustBeParent)) {
   277             return true;
   278         }
   279         for (ClassLoader scan2 = loader2;
   280                 scan2 != null; scan2 = scan2.getParent()) {
   281             if (scan2 == loader1)  return true;
   282         }
   283         if (loader1MustBeParent)  return false;
   284         // see if loader2 is a parent of loader1:
   285         for (ClassLoader scan1 = loader1;
   286                 scan1 != null; scan1 = scan1.getParent()) {
   287             if (scan1 == loader2)  return true;
   288         }
   289         return false;
   290     }
   291 
   292     /**
   293      * Is the class loader of parentClass identical to, or an ancestor of,
   294      * the class loader of childClass?
   295      * @param parentClass a class
   296      * @param childClass another class, which may be a descendent of the first class
   297      * @return whether parentClass precedes or equals childClass in class loader order
   298      */
   299     public static boolean classLoaderIsAncestor(Class<?> parentClass, Class<?> childClass) {
   300         return loadersAreRelated(parentClass.getClassLoader(), childClass.getClassLoader(), true);
   301     }
   302 }