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