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