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