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