emul/src/main/java/java/lang/reflect/AccessibleObject.java
branchjdk7-b147
changeset 258 21b390daf444
child 260 1d03cb35fbda
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/emul/src/main/java/java/lang/reflect/AccessibleObject.java	Tue Dec 04 13:29:17 2012 +0100
     1.3 @@ -0,0 +1,274 @@
     1.4 +/*
     1.5 + * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package java.lang.reflect;
    1.30 +
    1.31 +import java.security.AccessController;
    1.32 +import sun.reflect.Reflection;
    1.33 +import sun.reflect.ReflectionFactory;
    1.34 +import java.lang.annotation.Annotation;
    1.35 +
    1.36 +/**
    1.37 + * The AccessibleObject class is the base class for Field, Method and
    1.38 + * Constructor objects.  It provides the ability to flag a reflected
    1.39 + * object as suppressing default Java language access control checks
    1.40 + * when it is used.  The access checks--for public, default (package)
    1.41 + * access, protected, and private members--are performed when Fields,
    1.42 + * Methods or Constructors are used to set or get fields, to invoke
    1.43 + * methods, or to create and initialize new instances of classes,
    1.44 + * respectively.
    1.45 + *
    1.46 + * <p>Setting the {@code accessible} flag in a reflected object
    1.47 + * permits sophisticated applications with sufficient privilege, such
    1.48 + * as Java Object Serialization or other persistence mechanisms, to
    1.49 + * manipulate objects in a manner that would normally be prohibited.
    1.50 + *
    1.51 + * <p>By default, a reflected object is <em>not</em> accessible.
    1.52 + *
    1.53 + * @see Field
    1.54 + * @see Method
    1.55 + * @see Constructor
    1.56 + * @see ReflectPermission
    1.57 + *
    1.58 + * @since 1.2
    1.59 + */
    1.60 +public class AccessibleObject implements AnnotatedElement {
    1.61 +
    1.62 +    /**
    1.63 +     * The Permission object that is used to check whether a client
    1.64 +     * has sufficient privilege to defeat Java language access
    1.65 +     * control checks.
    1.66 +     */
    1.67 +    static final private java.security.Permission ACCESS_PERMISSION =
    1.68 +        new ReflectPermission("suppressAccessChecks");
    1.69 +
    1.70 +    /**
    1.71 +     * Convenience method to set the {@code accessible} flag for an
    1.72 +     * array of objects with a single security check (for efficiency).
    1.73 +     *
    1.74 +     * <p>First, if there is a security manager, its
    1.75 +     * {@code checkPermission} method is called with a
    1.76 +     * {@code ReflectPermission("suppressAccessChecks")} permission.
    1.77 +     *
    1.78 +     * <p>A {@code SecurityException} is raised if {@code flag} is
    1.79 +     * {@code true} but accessibility of any of the elements of the input
    1.80 +     * {@code array} may not be changed (for example, if the element
    1.81 +     * object is a {@link Constructor} object for the class {@link
    1.82 +     * java.lang.Class}).  In the event of such a SecurityException, the
    1.83 +     * accessibility of objects is set to {@code flag} for array elements
    1.84 +     * upto (and excluding) the element for which the exception occurred; the
    1.85 +     * accessibility of elements beyond (and including) the element for which
    1.86 +     * the exception occurred is unchanged.
    1.87 +     *
    1.88 +     * @param array the array of AccessibleObjects
    1.89 +     * @param flag  the new value for the {@code accessible} flag
    1.90 +     *              in each object
    1.91 +     * @throws SecurityException if the request is denied.
    1.92 +     * @see SecurityManager#checkPermission
    1.93 +     * @see java.lang.RuntimePermission
    1.94 +     */
    1.95 +    public static void setAccessible(AccessibleObject[] array, boolean flag)
    1.96 +        throws SecurityException {
    1.97 +        SecurityManager sm = System.getSecurityManager();
    1.98 +        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
    1.99 +        for (int i = 0; i < array.length; i++) {
   1.100 +            setAccessible0(array[i], flag);
   1.101 +        }
   1.102 +    }
   1.103 +
   1.104 +    /**
   1.105 +     * Set the {@code accessible} flag for this object to
   1.106 +     * the indicated boolean value.  A value of {@code true} indicates that
   1.107 +     * the reflected object should suppress Java language access
   1.108 +     * checking when it is used.  A value of {@code false} indicates
   1.109 +     * that the reflected object should enforce Java language access checks.
   1.110 +     *
   1.111 +     * <p>First, if there is a security manager, its
   1.112 +     * {@code checkPermission} method is called with a
   1.113 +     * {@code ReflectPermission("suppressAccessChecks")} permission.
   1.114 +     *
   1.115 +     * <p>A {@code SecurityException} is raised if {@code flag} is
   1.116 +     * {@code true} but accessibility of this object may not be changed
   1.117 +     * (for example, if this element object is a {@link Constructor} object for
   1.118 +     * the class {@link java.lang.Class}).
   1.119 +     *
   1.120 +     * <p>A {@code SecurityException} is raised if this object is a {@link
   1.121 +     * java.lang.reflect.Constructor} object for the class
   1.122 +     * {@code java.lang.Class}, and {@code flag} is true.
   1.123 +     *
   1.124 +     * @param flag the new value for the {@code accessible} flag
   1.125 +     * @throws SecurityException if the request is denied.
   1.126 +     * @see SecurityManager#checkPermission
   1.127 +     * @see java.lang.RuntimePermission
   1.128 +     */
   1.129 +    public void setAccessible(boolean flag) throws SecurityException {
   1.130 +        SecurityManager sm = System.getSecurityManager();
   1.131 +        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
   1.132 +        setAccessible0(this, flag);
   1.133 +    }
   1.134 +
   1.135 +    /* Check that you aren't exposing java.lang.Class.<init>. */
   1.136 +    private static void setAccessible0(AccessibleObject obj, boolean flag)
   1.137 +        throws SecurityException
   1.138 +    {
   1.139 +        if (obj instanceof Constructor && flag == true) {
   1.140 +            Constructor<?> c = (Constructor<?>)obj;
   1.141 +            if (c.getDeclaringClass() == Class.class) {
   1.142 +                throw new SecurityException("Can not make a java.lang.Class" +
   1.143 +                                            " constructor accessible");
   1.144 +            }
   1.145 +        }
   1.146 +        obj.override = flag;
   1.147 +    }
   1.148 +
   1.149 +    /**
   1.150 +     * Get the value of the {@code accessible} flag for this object.
   1.151 +     *
   1.152 +     * @return the value of the object's {@code accessible} flag
   1.153 +     */
   1.154 +    public boolean isAccessible() {
   1.155 +        return override;
   1.156 +    }
   1.157 +
   1.158 +    /**
   1.159 +     * Constructor: only used by the Java Virtual Machine.
   1.160 +     */
   1.161 +    protected AccessibleObject() {}
   1.162 +
   1.163 +    // Indicates whether language-level access checks are overridden
   1.164 +    // by this object. Initializes to "false". This field is used by
   1.165 +    // Field, Method, and Constructor.
   1.166 +    //
   1.167 +    // NOTE: for security purposes, this field must not be visible
   1.168 +    // outside this package.
   1.169 +    boolean override;
   1.170 +
   1.171 +    // Reflection factory used by subclasses for creating field,
   1.172 +    // method, and constructor accessors. Note that this is called
   1.173 +    // very early in the bootstrapping process.
   1.174 +    static final ReflectionFactory reflectionFactory =
   1.175 +        AccessController.doPrivileged(
   1.176 +            new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
   1.177 +
   1.178 +    /**
   1.179 +     * @throws NullPointerException {@inheritDoc}
   1.180 +     * @since 1.5
   1.181 +     */
   1.182 +    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
   1.183 +        throw new AssertionError("All subclasses should override this method");
   1.184 +    }
   1.185 +
   1.186 +    /**
   1.187 +     * @throws NullPointerException {@inheritDoc}
   1.188 +     * @since 1.5
   1.189 +     */
   1.190 +    public boolean isAnnotationPresent(
   1.191 +        Class<? extends Annotation> annotationClass) {
   1.192 +        return getAnnotation(annotationClass) != null;
   1.193 +    }
   1.194 +
   1.195 +    /**
   1.196 +     * @since 1.5
   1.197 +     */
   1.198 +    public Annotation[] getAnnotations() {
   1.199 +        return getDeclaredAnnotations();
   1.200 +    }
   1.201 +
   1.202 +    /**
   1.203 +     * @since 1.5
   1.204 +     */
   1.205 +    public Annotation[] getDeclaredAnnotations()  {
   1.206 +        throw new AssertionError("All subclasses should override this method");
   1.207 +    }
   1.208 +
   1.209 +
   1.210 +    // Shared access checking logic.
   1.211 +
   1.212 +    // For non-public members or members in package-private classes,
   1.213 +    // it is necessary to perform somewhat expensive security checks.
   1.214 +    // If the security check succeeds for a given class, it will
   1.215 +    // always succeed (it is not affected by the granting or revoking
   1.216 +    // of permissions); we speed up the check in the common case by
   1.217 +    // remembering the last Class for which the check succeeded.
   1.218 +    //
   1.219 +    // The simple security check for Constructor is to see if
   1.220 +    // the caller has already been seen, verified, and cached.
   1.221 +    // (See also Class.newInstance(), which uses a similar method.)
   1.222 +    //
   1.223 +    // A more complicated security check cache is needed for Method and Field
   1.224 +    // The cache can be either null (empty cache), a 2-array of {caller,target},
   1.225 +    // or a caller (with target implicitly equal to this.clazz).
   1.226 +    // In the 2-array case, the target is always different from the clazz.
   1.227 +    volatile Object securityCheckCache;
   1.228 +
   1.229 +    void checkAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers)
   1.230 +        throws IllegalAccessException
   1.231 +    {
   1.232 +        if (caller == clazz) {  // quick check
   1.233 +            return;             // ACCESS IS OK
   1.234 +        }
   1.235 +        Object cache = securityCheckCache;  // read volatile
   1.236 +        Class<?> targetClass = clazz;
   1.237 +        if (obj != null
   1.238 +            && Modifier.isProtected(modifiers)
   1.239 +            && ((targetClass = obj.getClass()) != clazz)) {
   1.240 +            // Must match a 2-list of { caller, targetClass }.
   1.241 +            if (cache instanceof Class[]) {
   1.242 +                Class<?>[] cache2 = (Class<?>[]) cache;
   1.243 +                if (cache2[1] == targetClass &&
   1.244 +                    cache2[0] == caller) {
   1.245 +                    return;     // ACCESS IS OK
   1.246 +                }
   1.247 +                // (Test cache[1] first since range check for [1]
   1.248 +                // subsumes range check for [0].)
   1.249 +            }
   1.250 +        } else if (cache == caller) {
   1.251 +            // Non-protected case (or obj.class == this.clazz).
   1.252 +            return;             // ACCESS IS OK
   1.253 +        }
   1.254 +
   1.255 +        // If no return, fall through to the slow path.
   1.256 +        slowCheckMemberAccess(caller, clazz, obj, modifiers, targetClass);
   1.257 +    }
   1.258 +
   1.259 +    // Keep all this slow stuff out of line:
   1.260 +    void slowCheckMemberAccess(Class<?> caller, Class<?> clazz, Object obj, int modifiers,
   1.261 +                               Class<?> targetClass)
   1.262 +        throws IllegalAccessException
   1.263 +    {
   1.264 +        Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
   1.265 +
   1.266 +        // Success: Update the cache.
   1.267 +        Object cache = ((targetClass == clazz)
   1.268 +                        ? caller
   1.269 +                        : new Class<?>[] { caller, targetClass });
   1.270 +
   1.271 +        // Note:  The two cache elements are not volatile,
   1.272 +        // but they are effectively final.  The Java memory model
   1.273 +        // guarantees that the initializing stores for the cache
   1.274 +        // elements will occur before the volatile write.
   1.275 +        securityCheckCache = cache;         // write volatile
   1.276 +    }
   1.277 +}