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