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