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 import sun.reflect.Reflection;
  31 
  32 /**
  33  * This class centralizes information about the JVM's linkage access control.
  34  * @author jrose
  35  */
  36 public class VerifyAccess {
  37 
  38     private VerifyAccess() { }  // cannot instantiate
  39 
  40     private static final int PACKAGE_ONLY = 0;
  41     private static final int PACKAGE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.PACKAGE;
  42     private static final int PROTECTED_OR_PACKAGE_ALLOWED = (PACKAGE_ALLOWED|PROTECTED);
  43     private static final int ALL_ACCESS_MODES = (PUBLIC|PRIVATE|PROTECTED|PACKAGE_ONLY);
  44     private static final boolean ALLOW_NESTMATE_ACCESS = false;
  45 
  46     /**
  47      * Evaluate the JVM linkage rules for access to the given method
  48      * on behalf of a caller class which proposes to perform the access.
  49      * Return true if the caller class has privileges to invoke a method
  50      * or access a field with the given properties.
  51      * This requires an accessibility check of the referencing class,
  52      * plus an accessibility check of the member within the class,
  53      * which depends on the member's modifier flags.
  54      * <p>
  55      * The relevant properties include the defining class ({@code defc})
  56      * of the member, and its modifier flags ({@code mods}).
  57      * Also relevant is the class used to make the initial symbolic reference
  58      * to the member ({@code refc}).  If this latter class is not distinguished,
  59      * the defining class should be passed for both arguments ({@code defc == refc}).
  60      * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
  61      * A field or method R is accessible to a class or interface D if
  62      * and only if any of the following conditions is true:<ul>
  63      * <li>R is public.
  64      * <li>R is protected and is declared in a class C, and D is either
  65      *     a subclass of C or C itself.  Furthermore, if R is not
  66      *     static, then the symbolic reference to R must contain a
  67      *     symbolic reference to a class T, such that T is either a
  68      *     subclass of D, a superclass of D or D itself.
  69      * <li>R is either protected or has default access (that is,
  70      *     neither public nor protected nor private), and is declared
  71      *     by a class in the same runtime package as D.
  72      * <li>R is private and is declared in D.
  73      * </ul>
  74      * This discussion of access control omits a related restriction
  75      * on the target of a protected field access or method invocation
  76      * (the target must be of class D or a subtype of D). That
  77      * requirement is checked as part of the verification process
  78      * (5.4.1); it is not part of link-time access control.
  79      * @param refc the class used in the symbolic reference to the proposed member
  80      * @param defc the class in which the proposed member is actually defined
  81      * @param mods modifier flags for the proposed member
  82      * @param lookupClass the class for which the access check is being made
  83      * @return true iff the the accessing class can access such a member
  84      */
  85     public static boolean isMemberAccessible(Class<?> refc,  // symbolic ref class
  86                                              Class<?> defc,  // actual def class
  87                                              int      mods,  // actual member mods
  88                                              Class<?> lookupClass,
  89                                              int      allowedModes) {
  90         if (allowedModes == 0)  return false;
  91         assert((allowedModes & PUBLIC) != 0 &&
  92                (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED)) == 0);
  93         // Usually refc and defc are the same, but if they differ, verify them both.
  94         if (refc != defc) {
  95             if (!isClassAccessible(refc, lookupClass, allowedModes)) {
  96                 // Note that defc is verified in the switch below.
  97                 return false;
  98             }
  99             if ((mods & (ALL_ACCESS_MODES|STATIC)) == (PROTECTED|STATIC) &&
 100                 (allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0) {
 101                 // Apply the special rules for refc here.
 102                 if (!isRelatedClass(refc, lookupClass))
 103                     return isSamePackage(defc, lookupClass);
 104                 // If refc == defc, the call to isPublicSuperClass will do
 105                 // the whole job, since in that case refc (as defc) will be
 106                 // a superclass of the lookup class.
 107             }
 108         }
 109         if (defc == lookupClass &&
 110             (allowedModes & PRIVATE) != 0)
 111             return true;        // easy check; all self-access is OK
 112         switch (mods & ALL_ACCESS_MODES) {
 113         case PUBLIC:
 114             if (refc != defc)  return true;  // already checked above
 115             return isClassAccessible(refc, lookupClass, allowedModes);
 116         case PROTECTED:
 117             if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
 118                 isSamePackage(defc, lookupClass))
 119                 return true;
 120             if ((allowedModes & PROTECTED) != 0 &&
 121                 isSuperClass(defc, lookupClass))
 122                 return true;
 123             return false;
 124         case PACKAGE_ONLY:  // That is, zero.  Unmarked member is package-only access.
 125             return ((allowedModes & PACKAGE_ALLOWED) != 0 &&
 126                     isSamePackage(defc, lookupClass));
 127         case PRIVATE:
 128             // Loosened rules for privates follows access rules for inner classes.
 129             return (ALLOW_NESTMATE_ACCESS &&
 130                     (allowedModes & PRIVATE) != 0 &&
 131                     isSamePackageMember(defc, lookupClass));
 132         default:
 133             throw new IllegalArgumentException("bad modifiers: "+Modifier.toString(mods));
 134         }
 135     }
 136 
 137     static boolean isRelatedClass(Class<?> refc, Class<?> lookupClass) {
 138         return (refc == lookupClass ||
 139                 refc.isAssignableFrom(lookupClass) ||
 140                 lookupClass.isAssignableFrom(refc));
 141     }
 142 
 143     static boolean isSuperClass(Class<?> defc, Class<?> lookupClass) {
 144         return defc.isAssignableFrom(lookupClass);
 145     }
 146 
 147     static int getClassModifiers(Class<?> c) {
 148         // This would return the mask stored by javac for the source-level modifiers.
 149         //   return c.getModifiers();
 150         // But what we need for JVM access checks are the actual bits from the class header.
 151         // ...But arrays and primitives are synthesized with their own odd flags:
 152         if (c.isArray() || c.isPrimitive())
 153             return c.getModifiers();
 154         return Reflection.getClassAccessFlags(c);
 155     }
 156 
 157     /**
 158      * Evaluate the JVM linkage rules for access to the given class on behalf of caller.
 159      * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
 160      * A class or interface C is accessible to a class or interface D
 161      * if and only if either of the following conditions are true:<ul>
 162      * <li>C is public.
 163      * <li>C and D are members of the same runtime package.
 164      * </ul>
 165      * @param refc the symbolic reference class to which access is being checked (C)
 166      * @param lookupClass the class performing the lookup (D)
 167      */
 168     public static boolean isClassAccessible(Class<?> refc, Class<?> lookupClass,
 169                                             int allowedModes) {
 170         if (allowedModes == 0)  return false;
 171         assert((allowedModes & PUBLIC) != 0 &&
 172                (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED)) == 0);
 173         int mods = getClassModifiers(refc);
 174         if (isPublic(mods))
 175             return true;
 176         if ((allowedModes & PACKAGE_ALLOWED) != 0 &&
 177             isSamePackage(lookupClass, refc))
 178             return true;
 179         return false;
 180     }
 181 
 182     /**
 183      * Decide if the given method type, attributed to a member or symbolic
 184      * reference of a given reference class, is really visible to that class.
 185      * @param type the supposed type of a member or symbolic reference of refc
 186      * @param refc the class attempting to make the reference
 187      */
 188     public static boolean isTypeVisible(Class<?> type, Class<?> refc) {
 189         if (type == refc)  return true;  // easy check
 190         while (type.isArray())  type = type.getComponentType();
 191         if (type.isPrimitive() || type == Object.class)  return true;
 192         ClassLoader parent = type.getClassLoader();
 193         if (parent == null)  return true;
 194         ClassLoader child  = refc.getClassLoader();
 195         if (child == null)  return false;
 196         if (parent == child || loadersAreRelated(parent, child, true))
 197             return true;
 198         // Do it the hard way:  Look up the type name from the refc loader.
 199         try {
 200             Class<?> res = child.loadClass(type.getName());
 201             return (type == res);
 202         } catch (ClassNotFoundException ex) {
 203             return false;
 204         }
 205     }
 206 
 207     /**
 208      * Decide if the given method type, attributed to a member or symbolic
 209      * reference of a given reference class, is really visible to that class.
 210      * @param type the supposed type of a member or symbolic reference of refc
 211      * @param refc the class attempting to make the reference
 212      */
 213     public static boolean isTypeVisible(java.lang.invoke.MethodType type, Class<?> refc) {
 214         for (int n = -1, max = type.parameterCount(); n < max; n++) {
 215             Class<?> ptype = (n < 0 ? type.returnType() : type.parameterType(n));
 216             if (!isTypeVisible(ptype, refc))
 217                 return false;
 218         }
 219         return true;
 220     }
 221 
 222     /**
 223      * Test if two classes have the same class loader and package qualifier.
 224      * @param class1 a class
 225      * @param class2 another class
 226      * @return whether they are in the same package
 227      */
 228     public static boolean isSamePackage(Class<?> class1, Class<?> class2) {
 229         assert(!class1.isArray() && !class2.isArray());
 230         if (class1 == class2)
 231             return true;
 232         if (class1.getClassLoader() != class2.getClassLoader())
 233             return false;
 234         String name1 = class1.getName(), name2 = class2.getName();
 235         int dot = name1.lastIndexOf('.');
 236         if (dot != name2.lastIndexOf('.'))
 237             return false;
 238         for (int i = 0; i < dot; i++) {
 239             if (name1.charAt(i) != name2.charAt(i))
 240                 return false;
 241         }
 242         return true;
 243     }
 244 
 245     /** Return the package name for this class.
 246      */
 247     public static String getPackageName(Class<?> cls) {
 248         assert(!cls.isArray());
 249         String name = cls.getName();
 250         int dot = name.lastIndexOf('.');
 251         if (dot < 0)  return "";
 252         return name.substring(0, dot);
 253     }
 254 
 255     /**
 256      * Test if two classes are defined as part of the same package member (top-level class).
 257      * If this is true, they can share private access with each other.
 258      * @param class1 a class
 259      * @param class2 another class
 260      * @return whether they are identical or nested together
 261      */
 262     public static boolean isSamePackageMember(Class<?> class1, Class<?> class2) {
 263         if (class1 == class2)
 264             return true;
 265         if (!isSamePackage(class1, class2))
 266             return false;
 267         if (getOutermostEnclosingClass(class1) != getOutermostEnclosingClass(class2))
 268             return false;
 269         return true;
 270     }
 271 
 272     private static Class<?> getOutermostEnclosingClass(Class<?> c) {
 273         Class<?> pkgmem = c;
 274         for (Class<?> enc = c; (enc = enc.getEnclosingClass()) != null; )
 275             pkgmem = enc;
 276         return pkgmem;
 277     }
 278 
 279     private static boolean loadersAreRelated(ClassLoader loader1, ClassLoader loader2,
 280                                              boolean loader1MustBeParent) {
 281         if (loader1 == loader2 || loader1 == null
 282                 || (loader2 == null && !loader1MustBeParent)) {
 283             return true;
 284         }
 285         for (ClassLoader scan2 = loader2;
 286                 scan2 != null; scan2 = scan2.getParent()) {
 287             if (scan2 == loader1)  return true;
 288         }
 289         if (loader1MustBeParent)  return false;
 290         // see if loader2 is a parent of loader1:
 291         for (ClassLoader scan1 = loader1;
 292                 scan1 != null; scan1 = scan1.getParent()) {
 293             if (scan1 == loader2)  return true;
 294         }
 295         return false;
 296     }
 297 
 298     /**
 299      * Is the class loader of parentClass identical to, or an ancestor of,
 300      * the class loader of childClass?
 301      * @param parentClass a class
 302      * @param childClass another class, which may be a descendent of the first class
 303      * @return whether parentClass precedes or equals childClass in class loader order
 304      */
 305     public static boolean classLoaderIsAncestor(Class<?> parentClass, Class<?> childClass) {
 306         return loadersAreRelated(parentClass.getClassLoader(), childClass.getClassLoader(), true);
 307     }
 308 }