1 /*
   2  * Copyright (c) 1997, 2016, 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.misc.VM;
  32 import jdk.internal.reflect.CallerSensitive;
  33 import jdk.internal.reflect.Reflection;
  34 import jdk.internal.reflect.ReflectionFactory;
  35 import sun.security.action.GetPropertyAction;
  36 
  37 /**
  38  * The AccessibleObject class is the base class for Field, Method and
  39  * Constructor objects.  It provides the ability to flag a reflected
  40  * object as suppressing default Java language access control checks
  41  * when it is used. The access checks -- <em>module boundaries</em>,
  42  * public, default (package) access, protected, and private members --
  43  * are performed when Fields, Methods or Constructors are used to set
  44  * or get fields, to invoke methods or to create and initialize new
  45  * instances of classes, respectively. Unlike access control specified
  46  * in the <cite>The Java&trade; Language Specification</cite> and
  47  * <cite>The Java Virtual Machine Specification</cite>, access checks
  48  * with reflected objects assume {@link Module#canRead readability}.
  49  *
  50  * <p>Setting the {@code accessible} flag in a reflected object
  51  * permits sophisticated applications with sufficient privilege, such
  52  * as Java Object Serialization or other persistence mechanisms, to
  53  * manipulate objects in a manner that would normally be prohibited.
  54  *
  55  * <p>By default, a reflected object is <em>not</em> accessible.
  56  *
  57  * @see Field
  58  * @see Method
  59  * @see Constructor
  60  * @see ReflectPermission
  61  *
  62  * @since 1.2
  63  */
  64 public class AccessibleObject implements AnnotatedElement {
  65 
  66     /**
  67      * The Permission object that is used to check whether a client
  68      * has sufficient privilege to defeat Java language access
  69      * control checks.
  70      */
  71     private static final java.security.Permission ACCESS_PERMISSION =
  72         new ReflectPermission("suppressAccessChecks");
  73 
  74     static void checkPermission() {
  75         SecurityManager sm = System.getSecurityManager();
  76         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
  77     }
  78 
  79     /**
  80      * Convenience method to set the {@code accessible} flag for an
  81      * array of objects with a single security check (for efficiency).
  82      *
  83      * <p>This method cannot be used to enable access to an object that is a
  84      * {@link Member member} of a class in a different module to the caller and
  85      * where the class is in a package that is not exported to the caller's
  86      * module. Additionally, if the member is non-public or its declaring
  87      * class is non-public, then this method can only be used to enable access
  88      * if the package is {@link Module#isOpen(String,Module) open} to at least
  89      * the caller's module.
  90      *
  91      * <p>If there is a security manager, its
  92      * {@code checkPermission} method is first called with a
  93      * {@code ReflectPermission("suppressAccessChecks")} permission.
  94      *
  95      * <p>A {@code SecurityException} is also thrown if any of the elements of
  96      * the input {@code array} is a {@link java.lang.reflect.Constructor}
  97      * object for the class {@code java.lang.Class} and {@code flag} is true.
  98      *
  99      * @param array the array of AccessibleObjects
 100      * @param flag  the new value for the {@code accessible} flag
 101      *              in each object
 102      * @throws InaccessibleObjectException if access cannot be enabled
 103      * @throws SecurityException if the request is denied.
 104      * @see SecurityManager#checkPermission
 105      * @see ReflectPermission
 106      */
 107     @CallerSensitive
 108     public static void setAccessible(AccessibleObject[] array, boolean flag) {
 109         checkPermission();
 110         if (flag) {
 111             Class<?> caller = Reflection.getCallerClass();
 112             array = array.clone();
 113             for (AccessibleObject ao : array) {
 114                 ao.checkCanSetAccessible(caller);
 115             }
 116         }
 117         for (AccessibleObject ao : array) {
 118             ao.setAccessible0(flag);
 119         }
 120     }
 121 
 122     /**
 123      * Set the {@code accessible} flag for this object to
 124      * the indicated boolean value.  A value of {@code true} indicates that
 125      * the reflected object should suppress Java language access
 126      * checking when it is used.  A value of {@code false} indicates
 127      * that the reflected object should enforce Java language access checks
 128      * while assuming readability (as noted in the class description).
 129      *
 130      * <p>This method cannot be used to enable access to an object that is a
 131      * {@link Member member} of a class in a different module to the caller and
 132      * where the class is in a package that is not exported to the caller's
 133      * module. Additionally, if the member is non-public or its declaring
 134      * class is non-public, then this method can only be used to enable access
 135      * if the package is {@link Module#isOpen(String,Module) open} to at least
 136      * the caller's module.
 137      *
 138      * <p>If there is a security manager, its
 139      * {@code checkPermission} method is first called with a
 140      * {@code ReflectPermission("suppressAccessChecks")} permission.
 141      *
 142      * @param flag the new value for the {@code accessible} flag
 143      * @throws InaccessibleObjectException if access cannot be enabled
 144      * @throws SecurityException if the request is denied
 145      * @see SecurityManager#checkPermission
 146      * @see ReflectPermission
 147      * @see java.lang.invoke.MethodHandles#privateLookupIn
 148      */
 149     public void setAccessible(boolean flag) {
 150         AccessibleObject.checkPermission();
 151         setAccessible0(flag);
 152     }
 153 
 154     void setAccessible0(boolean flag) {
 155         this.override = flag;
 156     }
 157 
 158    /**
 159     * If the given AccessibleObject is a {@code Constructor}, {@code Method}
 160     * or {@code Field} then checks that its declaring class is in a package
 161     * that can be accessed by the given caller of setAccessible.
 162     */
 163     void checkCanSetAccessible(Class<?> caller) {
 164         // do nothing, needs to be overridden by Constructor, Method, Field
 165     }
 166 
 167     void checkCanSetAccessible(Class<?> caller, Class<?> declaringClass) {
 168         Module callerModule = caller.getModule();
 169         Module declaringModule = declaringClass.getModule();
 170 
 171         if (callerModule == declaringModule) return;
 172         if (callerModule == Object.class.getModule()) return;
 173         if (!declaringModule.isNamed()) return;
 174 
 175         // package is open to caller
 176         String pn = packageName(declaringClass);
 177         if (declaringModule.isOpen(pn, callerModule)) {
 178             printStackTraceIfOpenedReflectively(declaringModule, pn, callerModule);
 179             return;
 180         }
 181 
 182         // package is exported to caller and class/member is public
 183         boolean isExported = declaringModule.isExported(pn, callerModule);
 184         boolean isClassPublic = Modifier.isPublic(declaringClass.getModifiers());
 185         int modifiers;
 186         if (this instanceof Executable) {
 187             modifiers = ((Executable) this).getModifiers();
 188         } else {
 189             modifiers = ((Field) this).getModifiers();
 190         }
 191         boolean isMemberPublic = Modifier.isPublic(modifiers);
 192         if (isExported && isClassPublic && isMemberPublic) {
 193             printStackTraceIfExportedReflectively(declaringModule, pn, callerModule);
 194             return;
 195         }
 196 
 197         // not accessible
 198         String msg = "Unable to make ";
 199         if (this instanceof Field)
 200             msg += "field ";
 201         msg += this + " accessible: " + declaringModule + " does not \"";
 202         if (isClassPublic && isMemberPublic)
 203             msg += "exports";
 204         else
 205             msg += "opens";
 206         msg += " " + pn + "\" to " + callerModule;
 207         InaccessibleObjectException e = new InaccessibleObjectException(msg);
 208         if (Reflection.printStackTraceWhenAccessFails()) {
 209             e.printStackTrace(System.err);
 210         }
 211         throw e;
 212     }
 213 
 214     private void printStackTraceIfOpenedReflectively(Module module,
 215                                                      String pn,
 216                                                      Module other) {
 217         printStackTraceIfExposedReflectively(module, pn, other, true);
 218     }
 219 
 220     private void printStackTraceIfExportedReflectively(Module module,
 221                                                        String pn,
 222                                                        Module other) {
 223         printStackTraceIfExposedReflectively(module, pn, other, false);
 224     }
 225 
 226     private static class WARNING extends Exception {
 227 
 228         private static final long serialVersionUID = 42L;
 229 
 230         private WARNING(String msg) {
 231             super(msg);
 232         }
 233 
 234         public String toString() {
 235             return "WARNING: " + getMessage();
 236         }
 237 
 238     }
 239 
 240     private void printStackTraceIfExposedReflectively(Module module,
 241                                                       String pn,
 242                                                       Module other,
 243                                                       boolean open) {
 244         if (Reflection.printStackTraceWhenAccessSucceeds()
 245                 && !module.isStaticallyExportedOrOpen(pn, other, open)) {
 246             String msg = other + " allowed to invoke setAccessible on ";
 247             if (this instanceof Field)
 248                 msg += "field ";
 249             msg += this;
 250             new WARNING(msg).printStackTrace(System.err);
 251         }
 252     }
 253 
 254     /**
 255      * Returns the package name of the given class.
 256      */
 257     private static String packageName(Class<?> c) {
 258         while (c.isArray()) {
 259             c = c.getComponentType();
 260         }
 261         String pn = c.getPackageName();
 262         return (pn != null) ? pn : "";
 263     }
 264 
 265     /**
 266      * Get the value of the {@code accessible} flag for this object.
 267      *
 268      * @return the value of the object's {@code accessible} flag
 269      */
 270     public boolean isAccessible() {
 271         return override;
 272     }
 273 
 274     /**
 275      * Constructor: only used by the Java Virtual Machine.
 276      */
 277     protected AccessibleObject() {}
 278 
 279     // Indicates whether language-level access checks are overridden
 280     // by this object. Initializes to "false". This field is used by
 281     // Field, Method, and Constructor.
 282     //
 283     // NOTE: for security purposes, this field must not be visible
 284     // outside this package.
 285     boolean override;
 286 
 287     // Reflection factory used by subclasses for creating field,
 288     // method, and constructor accessors. Note that this is called
 289     // very early in the bootstrapping process.
 290     static final ReflectionFactory reflectionFactory =
 291         AccessController.doPrivileged(
 292             new ReflectionFactory.GetReflectionFactoryAction());
 293 
 294     /**
 295      * @throws NullPointerException {@inheritDoc}
 296      * @since 1.5
 297      */
 298     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 299         throw new AssertionError("All subclasses should override this method");
 300     }
 301 
 302     /**
 303      * {@inheritDoc}
 304      * @throws NullPointerException {@inheritDoc}
 305      * @since 1.5
 306      */
 307     @Override
 308     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
 309         return AnnotatedElement.super.isAnnotationPresent(annotationClass);
 310     }
 311 
 312    /**
 313      * @throws NullPointerException {@inheritDoc}
 314      * @since 1.8
 315      */
 316     @Override
 317     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
 318         throw new AssertionError("All subclasses should override this method");
 319     }
 320 
 321     /**
 322      * @since 1.5
 323      */
 324     public Annotation[] getAnnotations() {
 325         return getDeclaredAnnotations();
 326     }
 327 
 328     /**
 329      * @throws NullPointerException {@inheritDoc}
 330      * @since 1.8
 331      */
 332     @Override
 333     public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
 334         // Only annotations on classes are inherited, for all other
 335         // objects getDeclaredAnnotation is the same as
 336         // getAnnotation.
 337         return getAnnotation(annotationClass);
 338     }
 339 
 340     /**
 341      * @throws NullPointerException {@inheritDoc}
 342      * @since 1.8
 343      */
 344     @Override
 345     public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
 346         // Only annotations on classes are inherited, for all other
 347         // objects getDeclaredAnnotationsByType is the same as
 348         // getAnnotationsByType.
 349         return getAnnotationsByType(annotationClass);
 350     }
 351 
 352     /**
 353      * @since 1.5
 354      */
 355     public Annotation[] getDeclaredAnnotations()  {
 356         throw new AssertionError("All subclasses should override this method");
 357     }
 358 
 359 
 360     // Shared access checking logic.
 361 
 362     // For non-public members or members in package-private classes,
 363     // it is necessary to perform somewhat expensive security checks.
 364     // If the security check succeeds for a given class, it will
 365     // always succeed (it is not affected by the granting or revoking
 366     // of permissions); we speed up the check in the common case by
 367     // remembering the last Class for which the check succeeded.
 368     //
 369     // The simple security check for Constructor is to see if
 370     // the caller has already been seen, verified, and cached.
 371     // (See also Class.newInstance(), which uses a similar method.)
 372     //
 373     // A more complicated security check cache is needed for Method and Field
 374     // The cache can be either null (empty cache), a 2-array of {caller,targetClass},
 375     // or a caller (with targetClass implicitly equal to memberClass).
 376     // In the 2-array case, the targetClass is always different from the memberClass.
 377     volatile Object securityCheckCache;
 378 
 379     final void checkAccess(Class<?> caller, Class<?> memberClass,
 380                            Class<?> targetClass, int modifiers)
 381         throws IllegalAccessException
 382     {
 383         if (caller == memberClass) {  // quick check
 384             return;             // ACCESS IS OK
 385         }
 386         Object cache = securityCheckCache;  // read volatile
 387         if (targetClass != null // instance member or constructor
 388             && Modifier.isProtected(modifiers)
 389             && targetClass != memberClass) {
 390             // Must match a 2-list of { caller, targetClass }.
 391             if (cache instanceof Class[]) {
 392                 Class<?>[] cache2 = (Class<?>[]) cache;
 393                 if (cache2[1] == targetClass &&
 394                     cache2[0] == caller) {
 395                     return;     // ACCESS IS OK
 396                 }
 397                 // (Test cache[1] first since range check for [1]
 398                 // subsumes range check for [0].)
 399             }
 400         } else if (cache == caller) {
 401             // Non-protected case (or targetClass == memberClass or static member).
 402             return;             // ACCESS IS OK
 403         }
 404 
 405         // If no return, fall through to the slow path.
 406         slowCheckMemberAccess(caller, memberClass, targetClass, modifiers);
 407     }
 408 
 409     // Keep all this slow stuff out of line:
 410     void slowCheckMemberAccess(Class<?> caller, Class<?> memberClass,
 411                                Class<?> targetClass, int modifiers)
 412         throws IllegalAccessException
 413     {
 414         Reflection.ensureMemberAccess(caller, memberClass, targetClass, modifiers);
 415 
 416         // Success: Update the cache.
 417         Object cache = (targetClass != null
 418                         && Modifier.isProtected(modifiers)
 419                         && targetClass != memberClass)
 420                         ? new Class<?>[] { caller, targetClass }
 421                         : caller;
 422 
 423         // Note:  The two cache elements are not volatile,
 424         // but they are effectively final.  The Java memory model
 425         // guarantees that the initializing stores for the cache
 426         // elements will occur before the volatile write.
 427         securityCheckCache = cache;         // write volatile
 428     }
 429 }