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