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