1/*
2 * Copyright (c) 1997, 2017, 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 java.lang.reflect;
27
28import java.lang.annotation.Annotation;
29import java.security.AccessController;
30
31import jdk.internal.misc.VM;
32import jdk.internal.module.IllegalAccessLogger;
33import jdk.internal.reflect.CallerSensitive;
34import jdk.internal.reflect.Reflection;
35import jdk.internal.reflect.ReflectionFactory;
36import sun.security.action.GetPropertyAction;
37
38/**
39 * The {@code AccessibleObject} class is the base class for {@code Field},
40 * {@code Method}, and {@code Constructor} objects (known as <em>reflected
41 * objects</em>). It provides the ability to flag a reflected object as
42 * suppressing checks for Java language access control when it is used. This
43 * permits sophisticated applications with sufficient privilege, such as Java
44 * Object Serialization or other persistence mechanisms, to manipulate objects
45 * in a manner that would normally be prohibited.
46 *
47 * <p> Java language access control prevents use of private members outside
48 * their class; package access members outside their package; protected members
49 * outside their package or subclasses; and public members outside their
50 * module unless they are declared in an {@link Module#isExported(String,Module)
51 * exported} package and the user {@link Module#canRead reads} their module. By
52 * default, Java language access control is enforced (with one variation) when
53 * {@code Field}s, {@code Method}s, or {@code Constructor}s are used to get or
54 * set fields, to invoke methods, or to create and initialize new instances of
55 * classes, respectively. Every reflected object checks that the code using it
56 * is in an appropriate class, package, or module. </p>
57 *
58 * <p> The one variation from Java language access control is that the checks
59 * by reflected objects assume readability. That is, the module containing
60 * the use of a reflected object is assumed to read the module in which
61 * the underlying field, method, or constructor is declared. </p>
62 *
63 * <p> Whether the checks for Java language access control can be suppressed
64 * (and thus, whether access can be enabled) depends on whether the reflected
65 * object corresponds to a member in an exported or open package
66 * (see {@link #setAccessible(boolean)}). </p>
67 *
68 * @jls 6.6 Access Control
69 * @since 1.2
70 * @revised 9
71 * @spec JPMS
72 */
73public class AccessibleObject implements AnnotatedElement {
74
75    /**
76     * The Permission object that is used to check whether a client
77     * has sufficient privilege to defeat Java language access
78     * control checks.
79     */
80    private static final java.security.Permission ACCESS_PERMISSION =
81        new ReflectPermission("suppressAccessChecks");
82
83    static void checkPermission() {
84        SecurityManager sm = System.getSecurityManager();
85        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
86    }
87
88    /**
89     * Convenience method to set the {@code accessible} flag for an
90     * array of reflected objects with a single security check (for efficiency).
91     *
92     * <p> This method may be used to enable access to all reflected objects in
93     * the array when access to each reflected object can be enabled as
94     * specified by {@link #setAccessible(boolean) setAccessible(boolean)}. </p>
95     *
96     * <p>If there is a security manager, its
97     * {@code checkPermission} method is first called with a
98     * {@code ReflectPermission("suppressAccessChecks")} permission.
99     *
100     * <p>A {@code SecurityException} is also thrown if any of the elements of
101     * the input {@code array} is a {@link java.lang.reflect.Constructor}
102     * object for the class {@code java.lang.Class} and {@code flag} is true.
103     *
104     * @param array the array of AccessibleObjects
105     * @param flag  the new value for the {@code accessible} flag
106     *              in each object
107     * @throws InaccessibleObjectException if access cannot be enabled for all
108     *         objects in the array
109     * @throws SecurityException if the request is denied by the security manager
110     *         or an element in the array is a constructor for {@code
111     *         java.lang.Class}
112     * @see SecurityManager#checkPermission
113     * @see ReflectPermission
114     * @revised 9
115     * @spec JPMS
116     */
117    @CallerSensitive
118    public static void setAccessible(AccessibleObject[] array, boolean flag) {
119        checkPermission();
120        if (flag) {
121            Class<?> caller = Reflection.getCallerClass();
122            array = array.clone();
123            for (AccessibleObject ao : array) {
124                ao.checkCanSetAccessible(caller);
125            }
126        }
127        for (AccessibleObject ao : array) {
128            ao.setAccessible0(flag);
129        }
130    }
131
132    /**
133     * Set the {@code accessible} flag for this reflected object to
134     * the indicated boolean value.  A value of {@code true} indicates that
135     * the reflected object should suppress checks for Java language access
136     * control when it is used. A value of {@code false} indicates that
137     * the reflected object should enforce checks for Java language access
138     * control when it is used, with the variation noted in the class description.
139     *
140     * <p> This method may be used by a caller in class {@code C} to enable
141     * access to a {@link Member member} of {@link Member#getDeclaringClass()
142     * declaring class} {@code D} if any of the following hold: </p>
143     *
144     * <ul>
145     *     <li> {@code C} and {@code D} are in the same module. </li>
146     *
147     *     <li> The member is {@code public} and {@code D} is {@code public} in
148     *     a package that the module containing {@code D} {@link
149     *     Module#isExported(String,Module) exports} to at least the module
150     *     containing {@code C}. </li>
151     *
152     *     <li> The member is {@code protected} {@code static}, {@code D} is
153     *     {@code public} in a package that the module containing {@code D}
154     *     exports to at least the module containing {@code C}, and {@code C}
155     *     is a subclass of {@code D}. </li>
156     *
157     *     <li> {@code D} is in a package that the module containing {@code D}
158     *     {@link Module#isOpen(String,Module) opens} to at least the module
159     *     containing {@code C}.
160     *     All packages in unnamed and open modules are open to all modules and
161     *     so this method always succeeds when {@code D} is in an unnamed or
162     *     open module. </li>
163     * </ul>
164     *
165     * <p> This method cannot be used to enable access to private members,
166     * members with default (package) access, protected instance members, or
167     * protected constructors when the declaring class is in a different module
168     * to the caller and the package containing the declaring class is not open
169     * to the caller's module. </p>
170     *
171     * <p> If there is a security manager, its
172     * {@code checkPermission} method is first called with a
173     * {@code ReflectPermission("suppressAccessChecks")} permission.
174     *
175     * @param flag the new value for the {@code accessible} flag
176     * @throws InaccessibleObjectException if access cannot be enabled
177     * @throws SecurityException if the request is denied by the security manager
178     * @see #trySetAccessible
179     * @see java.lang.invoke.MethodHandles#privateLookupIn
180     * @revised 9
181     * @spec JPMS
182     */
183    public void setAccessible(boolean flag) {
184        AccessibleObject.checkPermission();
185        setAccessible0(flag);
186    }
187
188    /**
189     * Sets the accessible flag and returns the new value
190     */
191    boolean setAccessible0(boolean flag) {
192        this.override = flag;
193        return flag;
194    }
195
196    /**
197     * Set the {@code accessible} flag for this reflected object to {@code true}
198     * if possible. This method sets the {@code accessible} flag, as if by
199     * invoking {@link #setAccessible(boolean) setAccessible(true)}, and returns
200     * the possibly-updated value for the {@code accessible} flag. If access
201     * cannot be enabled, i.e. the checks or Java language access control cannot
202     * be suppressed, this method returns {@code false} (as opposed to {@code
203     * setAccessible(true)} throwing {@code InaccessibleObjectException} when
204     * it fails).
205     *
206     * <p> This method is a no-op if the {@code accessible} flag for
207     * this reflected object is {@code true}.
208     *
209     * <p> For example, a caller can invoke {@code trySetAccessible}
210     * on a {@code Method} object for a private instance method
211     * {@code p.T::privateMethod} to suppress the checks for Java language access
212     * control when the {@code Method} is invoked.
213     * If {@code p.T} class is in a different module to the caller and
214     * package {@code p} is open to at least the caller's module,
215     * the code below successfully sets the {@code accessible} flag
216     * to {@code true}.
217     *
218     * <pre>
219     * {@code
220     *     p.T obj = ....;  // instance of p.T
221     *     :
222     *     Method m = p.T.class.getDeclaredMethod("privateMethod");
223     *     if (m.trySetAccessible()) {
224     *         m.invoke(obj);
225     *     } else {
226     *         // package p is not opened to the caller to access private member of T
227     *         ...
228     *     }
229     * }</pre>
230     *
231     * <p> If there is a security manager, its {@code checkPermission} method
232     * is first called with a {@code ReflectPermission("suppressAccessChecks")}
233     * permission. </p>
234     *
235     * @return {@code true} if the {@code accessible} flag is set to {@code true};
236     *         {@code false} if access cannot be enabled.
237     * @throws SecurityException if the request is denied by the security manager
238     *
239     * @since 9
240     * @spec JPMS
241     * @see java.lang.invoke.MethodHandles#privateLookupIn
242     */
243    @CallerSensitive
244    public final boolean trySetAccessible() {
245        AccessibleObject.checkPermission();
246
247        if (override == true) return true;
248
249        // if it's not a Constructor, Method, Field then no access check
250        if (!Member.class.isInstance(this)) {
251            return setAccessible0(true);
252        }
253
254        // does not allow to suppress access check for Class's constructor
255        Class<?> declaringClass = ((Member) this).getDeclaringClass();
256        if (declaringClass == Class.class && this instanceof Constructor) {
257            return false;
258        }
259
260        if (checkCanSetAccessible(Reflection.getCallerClass(),
261                                  declaringClass,
262                                  false)) {
263            return setAccessible0(true);
264        } else {
265            return false;
266        }
267    }
268
269
270   /**
271    * If the given AccessibleObject is a {@code Constructor}, {@code Method}
272    * or {@code Field} then checks that its declaring class is in a package
273    * that can be accessed by the given caller of setAccessible.
274    */
275    void checkCanSetAccessible(Class<?> caller) {
276        // do nothing, needs to be overridden by Constructor, Method, Field
277    }
278
279
280    void checkCanSetAccessible(Class<?> caller, Class<?> declaringClass) {
281        checkCanSetAccessible(caller, declaringClass, true);
282    }
283
284    private boolean checkCanSetAccessible(Class<?> caller,
285                                          Class<?> declaringClass,
286                                          boolean throwExceptionIfDenied) {
287        Module callerModule = caller.getModule();
288        Module declaringModule = declaringClass.getModule();
289
290        if (callerModule == declaringModule) return true;
291        if (callerModule == Object.class.getModule()) return true;
292        if (!declaringModule.isNamed()) return true;
293
294        String pn = declaringClass.getPackageName();
295        int modifiers;
296        if (this instanceof Executable) {
297            modifiers = ((Executable) this).getModifiers();
298        } else {
299            modifiers = ((Field) this).getModifiers();
300        }
301
302        // class is public and package is exported to caller
303        boolean isClassPublic = Modifier.isPublic(declaringClass.getModifiers());
304        if (isClassPublic && declaringModule.isExported(pn, callerModule)) {
305            // member is public
306            if (Modifier.isPublic(modifiers)) {
307                logIfExportedForIllegalAccess(caller, declaringClass);
308                return true;
309            }
310
311            // member is protected-static
312            if (Modifier.isProtected(modifiers)
313                && Modifier.isStatic(modifiers)
314                && isSubclassOf(caller, declaringClass)) {
315                logIfExportedForIllegalAccess(caller, declaringClass);
316                return true;
317            }
318        }
319
320        // package is open to caller
321        if (declaringModule.isOpen(pn, callerModule)) {
322            logIfOpenedForIllegalAccess(caller, declaringClass);
323            return true;
324        }
325
326        if (throwExceptionIfDenied) {
327            // not accessible
328            String msg = "Unable to make ";
329            if (this instanceof Field)
330                msg += "field ";
331            msg += this + " accessible: " + declaringModule + " does not \"";
332            if (isClassPublic && Modifier.isPublic(modifiers))
333                msg += "exports";
334            else
335                msg += "opens";
336            msg += " " + pn + "\" to " + callerModule;
337            InaccessibleObjectException e = new InaccessibleObjectException(msg);
338            if (printStackTraceWhenAccessFails()) {
339                e.printStackTrace(System.err);
340            }
341            throw e;
342        }
343        return false;
344    }
345
346    private boolean isSubclassOf(Class<?> queryClass, Class<?> ofClass) {
347        while (queryClass != null) {
348            if (queryClass == ofClass) {
349                return true;
350            }
351            queryClass = queryClass.getSuperclass();
352        }
353        return false;
354    }
355
356    private void logIfOpenedForIllegalAccess(Class<?> caller, Class<?> declaringClass) {
357        Module callerModule = caller.getModule();
358        Module targetModule = declaringClass.getModule();
359        // callerModule is null during early startup
360        if (callerModule != null && !callerModule.isNamed() && targetModule.isNamed()) {
361            IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
362            if (logger != null) {
363                logger.logIfOpenedForIllegalAccess(caller, declaringClass, this::toShortString);
364            }
365        }
366    }
367
368    private void logIfExportedForIllegalAccess(Class<?> caller, Class<?> declaringClass) {
369        Module callerModule = caller.getModule();
370        Module targetModule = declaringClass.getModule();
371        // callerModule is null during early startup
372        if (callerModule != null && !callerModule.isNamed() && targetModule.isNamed()) {
373            IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
374            if (logger != null) {
375                logger.logIfExportedForIllegalAccess(caller, declaringClass, this::toShortString);
376            }
377        }
378    }
379
380    /**
381     * Returns a short descriptive string to describe this object in log messages.
382     */
383    String toShortString() {
384        return toString();
385    }
386
387    /**
388     * Get the value of the {@code accessible} flag for this reflected object.
389     *
390     * @return the value of the object's {@code accessible} flag
391     *
392     * @deprecated
393     * This method is deprecated because its name hints that it checks
394     * if the reflected object is accessible when it actually indicates
395     * if the checks for Java language access control are suppressed.
396     * This method may return {@code false} on a reflected object that is
397     * accessible to the caller. To test if this reflected object is accessible,
398     * it should use {@link #canAccess(Object)}.
399     *
400     * @revised 9
401     * @spec JPMS
402     */
403    @Deprecated(since="9")
404    public boolean isAccessible() {
405        return override;
406    }
407
408    /**
409     * Test if the caller can access this reflected object. If this reflected
410     * object corresponds to an instance method or field then this method tests
411     * if the caller can access the given {@code obj} with the reflected object.
412     * For instance methods or fields then the {@code obj} argument must be an
413     * instance of the {@link Member#getDeclaringClass() declaring class}. For
414     * static members and constructors then {@code obj} must be {@code null}.
415     *
416     * <p> This method returns {@code true} if the {@code accessible} flag
417     * is set to {@code true}, i.e. the checks for Java language access control
418     * are suppressed, or if the caller can access the member as
419     * specified in <cite>The Java&trade; Language Specification</cite>,
420     * with the variation noted in the class description. </p>
421     *
422     * @param obj an instance object of the declaring class of this reflected
423     *            object if it is an instance method or field
424     *
425     * @return {@code true} if the caller can access this reflected object.
426     *
427     * @throws IllegalArgumentException
428     *         <ul>
429     *         <li> if this reflected object is a static member or constructor and
430     *              the given {@code obj} is non-{@code null}, or </li>
431     *         <li> if this reflected object is an instance method or field
432     *              and the given {@code obj} is {@code null} or of type
433     *              that is not a subclass of the {@link Member#getDeclaringClass()
434     *              declaring class} of the member.</li>
435     *         </ul>
436     *
437     * @since 9
438     * @spec JPMS
439     * @jls 6.6 Access Control
440     * @see #trySetAccessible
441     * @see #setAccessible(boolean)
442     */
443    @CallerSensitive
444    public final boolean canAccess(Object obj) {
445        if (!Member.class.isInstance(this)) {
446            return override;
447        }
448
449        Class<?> declaringClass = ((Member) this).getDeclaringClass();
450        int modifiers = ((Member) this).getModifiers();
451        if (!Modifier.isStatic(modifiers) &&
452                (this instanceof Method || this instanceof Field)) {
453            if (obj == null) {
454                throw new IllegalArgumentException("null object for " + this);
455            }
456            // if this object is an instance member, the given object
457            // must be a subclass of the declaring class of this reflected object
458            if (!declaringClass.isAssignableFrom(obj.getClass())) {
459                throw new IllegalArgumentException("object is not an instance of "
460                                                   + declaringClass.getName());
461            }
462        } else if (obj != null) {
463            throw new IllegalArgumentException("non-null object for " + this);
464        }
465
466        // access check is suppressed
467        if (override) return true;
468
469        Class<?> caller = Reflection.getCallerClass();
470        Class<?> targetClass;
471        if (this instanceof Constructor) {
472            targetClass = declaringClass;
473        } else {
474            targetClass = Modifier.isStatic(modifiers) ? null : obj.getClass();
475        }
476        return verifyAccess(caller, declaringClass, targetClass, modifiers);
477    }
478
479    /**
480     * Constructor: only used by the Java Virtual Machine.
481     */
482    protected AccessibleObject() {}
483
484    // Indicates whether language-level access checks are overridden
485    // by this object. Initializes to "false". This field is used by
486    // Field, Method, and Constructor.
487    //
488    // NOTE: for security purposes, this field must not be visible
489    // outside this package.
490    boolean override;
491
492    // Reflection factory used by subclasses for creating field,
493    // method, and constructor accessors. Note that this is called
494    // very early in the bootstrapping process.
495    static final ReflectionFactory reflectionFactory =
496        AccessController.doPrivileged(
497            new ReflectionFactory.GetReflectionFactoryAction());
498
499    /**
500     * @throws NullPointerException {@inheritDoc}
501     * @since 1.5
502     */
503    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
504        throw new AssertionError("All subclasses should override this method");
505    }
506
507    /**
508     * {@inheritDoc}
509     * @throws NullPointerException {@inheritDoc}
510     * @since 1.5
511     */
512    @Override
513    public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
514        return AnnotatedElement.super.isAnnotationPresent(annotationClass);
515    }
516
517    /**
518     * @throws NullPointerException {@inheritDoc}
519     * @since 1.8
520     */
521    @Override
522    public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
523        throw new AssertionError("All subclasses should override this method");
524    }
525
526    /**
527     * @since 1.5
528     */
529    public Annotation[] getAnnotations() {
530        return getDeclaredAnnotations();
531    }
532
533    /**
534     * @throws NullPointerException {@inheritDoc}
535     * @since 1.8
536     */
537    @Override
538    public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
539        // Only annotations on classes are inherited, for all other
540        // objects getDeclaredAnnotation is the same as
541        // getAnnotation.
542        return getAnnotation(annotationClass);
543    }
544
545    /**
546     * @throws NullPointerException {@inheritDoc}
547     * @since 1.8
548     */
549    @Override
550    public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
551        // Only annotations on classes are inherited, for all other
552        // objects getDeclaredAnnotationsByType is the same as
553        // getAnnotationsByType.
554        return getAnnotationsByType(annotationClass);
555    }
556
557    /**
558     * @since 1.5
559     */
560    public Annotation[] getDeclaredAnnotations()  {
561        throw new AssertionError("All subclasses should override this method");
562    }
563
564
565    // Shared access checking logic.
566
567    // For non-public members or members in package-private classes,
568    // it is necessary to perform somewhat expensive security checks.
569    // If the security check succeeds for a given class, it will
570    // always succeed (it is not affected by the granting or revoking
571    // of permissions); we speed up the check in the common case by
572    // remembering the last Class for which the check succeeded.
573    //
574    // The simple security check for Constructor is to see if
575    // the caller has already been seen, verified, and cached.
576    // (See also Class.newInstance(), which uses a similar method.)
577    //
578    // A more complicated security check cache is needed for Method and Field
579    // The cache can be either null (empty cache), a 2-array of {caller,targetClass},
580    // or a caller (with targetClass implicitly equal to memberClass).
581    // In the 2-array case, the targetClass is always different from the memberClass.
582    volatile Object securityCheckCache;
583
584    final void checkAccess(Class<?> caller, Class<?> memberClass,
585                           Class<?> targetClass, int modifiers)
586        throws IllegalAccessException
587    {
588        if (!verifyAccess(caller, memberClass, targetClass, modifiers)) {
589            IllegalAccessException e = Reflection.newIllegalAccessException(
590                caller, memberClass, targetClass, modifiers);
591            if (printStackTraceWhenAccessFails()) {
592                e.printStackTrace(System.err);
593            }
594            throw e;
595        }
596    }
597
598    final boolean verifyAccess(Class<?> caller, Class<?> memberClass,
599                               Class<?> targetClass, int modifiers)
600    {
601        if (caller == memberClass) {  // quick check
602            return true;             // ACCESS IS OK
603        }
604        Object cache = securityCheckCache;  // read volatile
605        if (targetClass != null // instance member or constructor
606            && Modifier.isProtected(modifiers)
607            && targetClass != memberClass) {
608            // Must match a 2-list of { caller, targetClass }.
609            if (cache instanceof Class[]) {
610                Class<?>[] cache2 = (Class<?>[]) cache;
611                if (cache2[1] == targetClass &&
612                    cache2[0] == caller) {
613                    return true;     // ACCESS IS OK
614                }
615                // (Test cache[1] first since range check for [1]
616                // subsumes range check for [0].)
617            }
618        } else if (cache == caller) {
619            // Non-protected case (or targetClass == memberClass or static member).
620            return true;             // ACCESS IS OK
621        }
622
623        // If no return, fall through to the slow path.
624        return slowVerifyAccess(caller, memberClass, targetClass, modifiers);
625    }
626
627    // Keep all this slow stuff out of line:
628    private boolean slowVerifyAccess(Class<?> caller, Class<?> memberClass,
629                                     Class<?> targetClass, int modifiers)
630    {
631        if (!Reflection.verifyMemberAccess(caller, memberClass, targetClass, modifiers)) {
632            // access denied
633            return false;
634        }
635
636        // access okay
637        logIfExportedForIllegalAccess(caller, memberClass);
638
639        // Success: Update the cache.
640        Object cache = (targetClass != null
641                        && Modifier.isProtected(modifiers)
642                        && targetClass != memberClass)
643                        ? new Class<?>[] { caller, targetClass }
644                        : caller;
645
646        // Note:  The two cache elements are not volatile,
647        // but they are effectively final.  The Java memory model
648        // guarantees that the initializing stores for the cache
649        // elements will occur before the volatile write.
650        securityCheckCache = cache;         // write volatile
651        return true;
652    }
653
654    // true to print a stack trace when access fails
655    private static volatile boolean printStackWhenAccessFails;
656
657    // true if printStack* values are initialized
658    private static volatile boolean printStackPropertiesSet;
659
660    /**
661     * Returns true if a stack trace should be printed when access fails.
662     */
663    private static boolean printStackTraceWhenAccessFails() {
664        if (!printStackPropertiesSet && VM.initLevel() >= 1) {
665            String s = GetPropertyAction.privilegedGetProperty(
666                    "sun.reflect.debugModuleAccessChecks");
667            if (s != null) {
668                printStackWhenAccessFails = !s.equalsIgnoreCase("false");
669            }
670            printStackPropertiesSet = true;
671        }
672        return printStackWhenAccessFails;
673    }
674}
675