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