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