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