VerifyAccess.java revision 13901:b2a69d66dc65
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
26package sun.invoke.util;
27
28import java.lang.reflect.Modifier;
29import static java.lang.reflect.Modifier.*;
30import java.lang.reflect.Module;
31import sun.reflect.Reflection;
32
33/**
34 * This class centralizes information about the JVM's linkage access control.
35 * @author jrose
36 */
37public class VerifyAccess {
38
39    private VerifyAccess() { }  // cannot instantiate
40
41    private static final int MODULE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.MODULE;
42    private static final int PACKAGE_ONLY = 0;
43    private static final int PACKAGE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.PACKAGE;
44    private static final int PROTECTED_OR_PACKAGE_ALLOWED = (PACKAGE_ALLOWED|PROTECTED);
45    private static final int ALL_ACCESS_MODES = (PUBLIC|PRIVATE|PROTECTED|PACKAGE_ONLY);
46    private static final boolean ALLOW_NESTMATE_ACCESS = false;
47
48    /**
49     * Evaluate the JVM linkage rules for access to the given method
50     * on behalf of a caller class which proposes to perform the access.
51     * Return true if the caller class has privileges to invoke a method
52     * or access a field with the given properties.
53     * This requires an accessibility check of the referencing class,
54     * plus an accessibility check of the member within the class,
55     * which depends on the member's modifier flags.
56     * <p>
57     * The relevant properties include the defining class ({@code defc})
58     * of the member, and its modifier flags ({@code mods}).
59     * Also relevant is the class used to make the initial symbolic reference
60     * to the member ({@code refc}).  If this latter class is not distinguished,
61     * the defining class should be passed for both arguments ({@code defc == refc}).
62     * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
63     * A field or method R is accessible to a class or interface D if
64     * and only if any of the following conditions is true:<ul>
65     * <li>R is public.
66     * <li>R is protected and is declared in a class C, and D is either
67     *     a subclass of C or C itself.  Furthermore, if R is not
68     *     static, then the symbolic reference to R must contain a
69     *     symbolic reference to a class T, such that T is either a
70     *     subclass of D, a superclass of D or D itself.
71     * <li>R is either protected or has default access (that is,
72     *     neither public nor protected nor private), and is declared
73     *     by a class in the same runtime package as D.
74     * <li>R is private and is declared in D.
75     * </ul>
76     * This discussion of access control omits a related restriction
77     * on the target of a protected field access or method invocation
78     * (the target must be of class D or a subtype of D). That
79     * requirement is checked as part of the verification process
80     * (5.4.1); it is not part of link-time access control.
81     * @param refc the class used in the symbolic reference to the proposed member
82     * @param defc the class in which the proposed member is actually defined
83     * @param mods modifier flags for the proposed member
84     * @param lookupClass the class for which the access check is being made
85     * @return true iff the accessing class can access such a member
86     */
87    public static boolean isMemberAccessible(Class<?> refc,  // symbolic ref class
88                                             Class<?> defc,  // actual def class
89                                             int      mods,  // actual member mods
90                                             Class<?> lookupClass,
91                                             int      allowedModes) {
92        if (allowedModes == 0)  return false;
93        assert((allowedModes & PUBLIC) != 0 &&
94               (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED)) == 0);
95        // The symbolic reference class (refc) must always be fully verified.
96        if (!isClassAccessible(refc, lookupClass, allowedModes)) {
97            return false;
98        }
99        // Usually refc and defc are the same, but verify defc also in case they differ.
100        if (defc == lookupClass &&
101            (allowedModes & PRIVATE) != 0)
102            return true;        // easy check; all self-access is OK
103        switch (mods & ALL_ACCESS_MODES) {
104        case PUBLIC:
105            return true;  // already checked above
106        case PROTECTED:
107            assert !defc.isInterface(); // protected members aren't allowed in interfaces
108            if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
109                isSamePackage(defc, lookupClass))
110                return true;
111            if ((allowedModes & PROTECTED) == 0)
112                return false;
113            // Protected members are accessible by subclasses, which does not include interfaces.
114            // Interfaces are types, not classes. They should not have access to
115            // protected members in j.l.Object, even though it is their superclass.
116            if ((mods & STATIC) != 0 &&
117                !isRelatedClass(refc, lookupClass))
118                return false;
119            if ((allowedModes & PROTECTED) != 0 &&
120                isSubClass(lookupClass, defc))
121                return true;
122            return false;
123        case PACKAGE_ONLY:  // That is, zero.  Unmarked member is package-only access.
124            assert !defc.isInterface(); // package-private members aren't allowed in interfaces
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                isSubClass(refc, lookupClass) ||
140                isSubClass(lookupClass, refc));
141    }
142
143    static boolean isSubClass(Class<?> lookupClass, Class<?> defc) {
144        return defc.isAssignableFrom(lookupClass) &&
145               !lookupClass.isInterface(); // interfaces are types, not classes.
146    }
147
148    static int getClassModifiers(Class<?> c) {
149        // This would return the mask stored by javac for the source-level modifiers.
150        //   return c.getModifiers();
151        // But what we need for JVM access checks are the actual bits from the class header.
152        // ...But arrays and primitives are synthesized with their own odd flags:
153        if (c.isArray() || c.isPrimitive())
154            return c.getModifiers();
155        return Reflection.getClassAccessFlags(c);
156    }
157
158    /**
159     * Evaluate the JVM linkage rules for access to the given class on behalf of caller.
160     * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
161     * A class or interface C is accessible to a class or interface D
162     * if and only if any of the following conditions are true:<ul>
163     * <li>C is public and in the same module as D.
164     * <li>D is in a module that reads the module containing C, C is public and in a
165     * package that is exported to the module that contains D.
166     * <li>C and D are members of the same runtime package.
167     * </ul>
168     * @param refc the symbolic reference class to which access is being checked (C)
169     * @param lookupClass the class performing the lookup (D)
170     */
171    public static boolean isClassAccessible(Class<?> refc, Class<?> lookupClass,
172                                            int allowedModes) {
173        if (allowedModes == 0)  return false;
174        assert((allowedModes & PUBLIC) != 0 &&
175               (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED)) == 0);
176        int mods = getClassModifiers(refc);
177        if (isPublic(mods)) {
178
179            Module lookupModule = lookupClass.getModule();
180            Module refModule = refc.getModule();
181
182            // early VM startup case, java.base not defined
183            if (lookupModule == null) {
184                assert refModule == null;
185                return true;
186            }
187
188            // trivially allow
189            if ((allowedModes & MODULE_ALLOWED) != 0 &&
190                (lookupModule == refModule))
191                return true;
192
193            // check readability
194            if (lookupModule.canRead(refModule)) {
195
196                // check that refc is in an exported package
197                Class<?> c = refc;
198                while (c.isArray()) {
199                    c = c.getComponentType();
200                }
201                if (c.isPrimitive())
202                    return true;
203                if ((allowedModes & MODULE_ALLOWED) != 0) {
204                    if (refModule.isExported(c.getPackageName(), lookupModule))
205                        return true;
206                } else {
207                    // exported unconditionally
208                    if (refModule.isExported(c.getPackageName()))
209                        return true;
210                }
211
212                // not exported but allow access during VM initialization
213                // because java.base does not have its exports setup
214                if (!jdk.internal.misc.VM.isModuleSystemInited())
215                    return true;
216            }
217
218            // public class not accessible to lookupClass
219            return false;
220        }
221        if ((allowedModes & PACKAGE_ALLOWED) != 0 &&
222            isSamePackage(lookupClass, refc))
223            return true;
224        return false;
225    }
226
227    /**
228     * Decide if the given method type, attributed to a member or symbolic
229     * reference of a given reference class, is really visible to that class.
230     * @param type the supposed type of a member or symbolic reference of refc
231     * @param refc the class attempting to make the reference
232     */
233    public static boolean isTypeVisible(Class<?> type, Class<?> refc) {
234        if (type == refc)  return true;  // easy check
235        while (type.isArray())  type = type.getComponentType();
236        if (type.isPrimitive() || type == Object.class)  return true;
237        ClassLoader parent = type.getClassLoader();
238        if (parent == null)  return true;
239        ClassLoader child  = refc.getClassLoader();
240        if (child == null)  return false;
241        if (parent == child || loadersAreRelated(parent, child, true))
242            return true;
243        // Do it the hard way:  Look up the type name from the refc loader.
244        try {
245            Class<?> res = child.loadClass(type.getName());
246            return (type == res);
247        } catch (ClassNotFoundException ex) {
248            return false;
249        }
250    }
251
252    /**
253     * Decide if the given method type, attributed to a member or symbolic
254     * reference of a given reference class, is really visible to that class.
255     * @param type the supposed type of a member or symbolic reference of refc
256     * @param refc the class attempting to make the reference
257     */
258    public static boolean isTypeVisible(java.lang.invoke.MethodType type, Class<?> refc) {
259        for (int n = -1, max = type.parameterCount(); n < max; n++) {
260            Class<?> ptype = (n < 0 ? type.returnType() : type.parameterType(n));
261            if (!isTypeVisible(ptype, refc))
262                return false;
263        }
264        return true;
265    }
266
267    /**
268     * Tests if two classes are in the same module.
269     * @param class1 a class
270     * @param class2 another class
271     * @return whether they are in the same module
272     */
273    public static boolean isSameModule(Class<?> class1, Class<?> class2) {
274        return class1.getModule() == class2.getModule();
275    }
276
277    /**
278     * Test if two classes have the same class loader and package qualifier.
279     * @param class1 a class
280     * @param class2 another class
281     * @return whether they are in the same package
282     */
283    public static boolean isSamePackage(Class<?> class1, Class<?> class2) {
284        assert(!class1.isArray() && !class2.isArray());
285        if (class1 == class2)
286            return true;
287        if (class1.getClassLoader() != class2.getClassLoader())
288            return false;
289        String name1 = class1.getName(), name2 = class2.getName();
290        int dot = name1.lastIndexOf('.');
291        if (dot != name2.lastIndexOf('.'))
292            return false;
293        for (int i = 0; i < dot; i++) {
294            if (name1.charAt(i) != name2.charAt(i))
295                return false;
296        }
297        return true;
298    }
299
300    /** Return the package name for this class.
301     */
302    public static String getPackageName(Class<?> cls) {
303        assert (!cls.isArray());
304        String name = cls.getName();
305        int dot = name.lastIndexOf('.');
306        if (dot < 0) return "";
307        return name.substring(0, dot);
308    }
309
310    /**
311     * Test if two classes are defined as part of the same package member (top-level class).
312     * If this is true, they can share private access with each other.
313     * @param class1 a class
314     * @param class2 another class
315     * @return whether they are identical or nested together
316     */
317    public static boolean isSamePackageMember(Class<?> class1, Class<?> class2) {
318        if (class1 == class2)
319            return true;
320        if (!isSamePackage(class1, class2))
321            return false;
322        if (getOutermostEnclosingClass(class1) != getOutermostEnclosingClass(class2))
323            return false;
324        return true;
325    }
326
327    private static Class<?> getOutermostEnclosingClass(Class<?> c) {
328        Class<?> pkgmem = c;
329        for (Class<?> enc = c; (enc = enc.getEnclosingClass()) != null; )
330            pkgmem = enc;
331        return pkgmem;
332    }
333
334    private static boolean loadersAreRelated(ClassLoader loader1, ClassLoader loader2,
335                                             boolean loader1MustBeParent) {
336        if (loader1 == loader2 || loader1 == null
337                || (loader2 == null && !loader1MustBeParent)) {
338            return true;
339        }
340        for (ClassLoader scan2 = loader2;
341                scan2 != null; scan2 = scan2.getParent()) {
342            if (scan2 == loader1)  return true;
343        }
344        if (loader1MustBeParent)  return false;
345        // see if loader2 is a parent of loader1:
346        for (ClassLoader scan1 = loader1;
347                scan1 != null; scan1 = scan1.getParent()) {
348            if (scan1 == loader2)  return true;
349        }
350        return false;
351    }
352
353    /**
354     * Is the class loader of parentClass identical to, or an ancestor of,
355     * the class loader of childClass?
356     * @param parentClass a class
357     * @param childClass another class, which may be a descendent of the first class
358     * @return whether parentClass precedes or equals childClass in class loader order
359     */
360    public static boolean classLoaderIsAncestor(Class<?> parentClass, Class<?> childClass) {
361        return loadersAreRelated(parentClass.getClassLoader(), childClass.getClassLoader(), true);
362    }
363}
364