1 /*
   2  * Copyright (c) 2001, 2013, 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 jdk.internal.reflect;
  27 
  28 import java.lang.reflect.Field;
  29 import java.lang.reflect.Executable;
  30 import java.lang.reflect.Method;
  31 import java.lang.reflect.Constructor;
  32 import java.lang.reflect.Modifier;
  33 import java.security.Permission;
  34 import java.security.PrivilegedAction;
  35 import java.util.Properties;
  36 import sun.reflect.misc.ReflectUtil;
  37 import sun.security.action.GetPropertyAction;
  38 
  39 /** <P> The master factory for all reflective objects, both those in
  40     java.lang.reflect (Fields, Methods, Constructors) as well as their
  41     delegates (FieldAccessors, MethodAccessors, ConstructorAccessors).
  42     </P>
  43 
  44     <P> The methods in this class are extremely unsafe and can cause
  45     subversion of both the language and the verifier. For this reason,
  46     they are all instance methods, and access to the constructor of
  47     this factory is guarded by a security check, in similar style to
  48     {@link jdk.internal.misc.Unsafe}. </P>
  49 */
  50 
  51 public class ReflectionFactory {
  52 
  53     private static boolean initted = false;
  54     private static final Permission reflectionFactoryAccessPerm
  55         = new RuntimePermission("reflectionFactoryAccess");
  56     private static final ReflectionFactory soleInstance = new ReflectionFactory();
  57     // Provides access to package-private mechanisms in java.lang.reflect
  58     private static volatile LangReflectAccess langReflectAccess;
  59 
  60     //
  61     // "Inflation" mechanism. Loading bytecodes to implement
  62     // Method.invoke() and Constructor.newInstance() currently costs
  63     // 3-4x more than an invocation via native code for the first
  64     // invocation (though subsequent invocations have been benchmarked
  65     // to be over 20x faster). Unfortunately this cost increases
  66     // startup time for certain applications that use reflection
  67     // intensively (but only once per class) to bootstrap themselves.
  68     // To avoid this penalty we reuse the existing JVM entry points
  69     // for the first few invocations of Methods and Constructors and
  70     // then switch to the bytecode-based implementations.
  71     //
  72     // Package-private to be accessible to NativeMethodAccessorImpl
  73     // and NativeConstructorAccessorImpl
  74     private static boolean noInflation        = false;
  75     private static int     inflationThreshold = 15;
  76 
  77     private ReflectionFactory() {
  78     }
  79 
  80     /**
  81      * A convenience class for acquiring the capability to instantiate
  82      * reflective objects.  Use this instead of a raw call to {@link
  83      * #getReflectionFactory} in order to avoid being limited by the
  84      * permissions of your callers.
  85      *
  86      * <p>An instance of this class can be used as the argument of
  87      * <code>AccessController.doPrivileged</code>.
  88      */
  89     public static final class GetReflectionFactoryAction
  90         implements PrivilegedAction<ReflectionFactory> {
  91         public ReflectionFactory run() {
  92             return getReflectionFactory();
  93         }
  94     }
  95 
  96     /**
  97      * Provides the caller with the capability to instantiate reflective
  98      * objects.
  99      *
 100      * <p> First, if there is a security manager, its
 101      * <code>checkPermission</code> method is called with a {@link
 102      * java.lang.RuntimePermission} with target
 103      * <code>"reflectionFactoryAccess"</code>.  This may result in a
 104      * security exception.
 105      *
 106      * <p> The returned <code>ReflectionFactory</code> object should be
 107      * carefully guarded by the caller, since it can be used to read and
 108      * write private data and invoke private methods, as well as to load
 109      * unverified bytecodes.  It must never be passed to untrusted code.
 110      *
 111      * @exception SecurityException if a security manager exists and its
 112      *             <code>checkPermission</code> method doesn't allow
 113      *             access to the RuntimePermission "reflectionFactoryAccess".  */
 114     public static ReflectionFactory getReflectionFactory() {
 115         SecurityManager security = System.getSecurityManager();
 116         if (security != null) {
 117             // TO DO: security.checkReflectionFactoryAccess();
 118             security.checkPermission(reflectionFactoryAccessPerm);
 119         }
 120         return soleInstance;
 121     }
 122 
 123     //--------------------------------------------------------------------------
 124     //
 125     // Routines used by java.lang.reflect
 126     //
 127     //
 128 
 129     /** Called only by java.lang.reflect.Modifier's static initializer */
 130     public void setLangReflectAccess(LangReflectAccess access) {
 131         langReflectAccess = access;
 132     }
 133 
 134     /**
 135      * Note: this routine can cause the declaring class for the field
 136      * be initialized and therefore must not be called until the
 137      * first get/set of this field.
 138      * @param field the field
 139      * @param override true if caller has overridden accessibility
 140      */
 141     public FieldAccessor newFieldAccessor(Field field, boolean override) {
 142         checkInitted();
 143         return UnsafeFieldAccessorFactory.newFieldAccessor(field, override);
 144     }
 145 
 146     public MethodAccessor newMethodAccessor(Method method) {
 147         checkInitted();
 148 
 149         if (noInflation && !ReflectUtil.isVMAnonymousClass(method.getDeclaringClass())) {
 150             return new MethodAccessorGenerator().
 151                 generateMethod(method.getDeclaringClass(),
 152                                method.getName(),
 153                                method.getParameterTypes(),
 154                                method.getReturnType(),
 155                                method.getExceptionTypes(),
 156                                method.getModifiers());
 157         } else {
 158             NativeMethodAccessorImpl acc =
 159                 new NativeMethodAccessorImpl(method);
 160             DelegatingMethodAccessorImpl res =
 161                 new DelegatingMethodAccessorImpl(acc);
 162             acc.setParent(res);
 163             return res;
 164         }
 165     }
 166 
 167     public ConstructorAccessor newConstructorAccessor(Constructor<?> c) {
 168         checkInitted();
 169 
 170         Class<?> declaringClass = c.getDeclaringClass();
 171         if (Modifier.isAbstract(declaringClass.getModifiers())) {
 172             return new InstantiationExceptionConstructorAccessorImpl(null);
 173         }
 174         if (declaringClass == Class.class) {
 175             return new InstantiationExceptionConstructorAccessorImpl
 176                 ("Can not instantiate java.lang.Class");
 177         }
 178         // Bootstrapping issue: since we use Class.newInstance() in
 179         // the ConstructorAccessor generation process, we have to
 180         // break the cycle here.
 181         if (Reflection.isSubclassOf(declaringClass,
 182                                     ConstructorAccessorImpl.class)) {
 183             return new BootstrapConstructorAccessorImpl(c);
 184         }
 185 
 186         if (noInflation && !ReflectUtil.isVMAnonymousClass(c.getDeclaringClass())) {
 187             return new MethodAccessorGenerator().
 188                 generateConstructor(c.getDeclaringClass(),
 189                                     c.getParameterTypes(),
 190                                     c.getExceptionTypes(),
 191                                     c.getModifiers());
 192         } else {
 193             NativeConstructorAccessorImpl acc =
 194                 new NativeConstructorAccessorImpl(c);
 195             DelegatingConstructorAccessorImpl res =
 196                 new DelegatingConstructorAccessorImpl(acc);
 197             acc.setParent(res);
 198             return res;
 199         }
 200     }
 201 
 202     //--------------------------------------------------------------------------
 203     //
 204     // Routines used by java.lang
 205     //
 206     //
 207 
 208     /** Creates a new java.lang.reflect.Field. Access checks as per
 209         java.lang.reflect.AccessibleObject are not overridden. */
 210     public Field newField(Class<?> declaringClass,
 211                           String name,
 212                           Class<?> type,
 213                           int modifiers,
 214                           int slot,
 215                           String signature,
 216                           byte[] annotations)
 217     {
 218         return langReflectAccess().newField(declaringClass,
 219                                             name,
 220                                             type,
 221                                             modifiers,
 222                                             slot,
 223                                             signature,
 224                                             annotations);
 225     }
 226 
 227     /** Creates a new java.lang.reflect.Method. Access checks as per
 228         java.lang.reflect.AccessibleObject are not overridden. */
 229     public Method newMethod(Class<?> declaringClass,
 230                             String name,
 231                             Class<?>[] parameterTypes,
 232                             Class<?> returnType,
 233                             Class<?>[] checkedExceptions,
 234                             int modifiers,
 235                             int slot,
 236                             String signature,
 237                             byte[] annotations,
 238                             byte[] parameterAnnotations,
 239                             byte[] annotationDefault)
 240     {
 241         return langReflectAccess().newMethod(declaringClass,
 242                                              name,
 243                                              parameterTypes,
 244                                              returnType,
 245                                              checkedExceptions,
 246                                              modifiers,
 247                                              slot,
 248                                              signature,
 249                                              annotations,
 250                                              parameterAnnotations,
 251                                              annotationDefault);
 252     }
 253 
 254     /** Creates a new java.lang.reflect.Constructor. Access checks as
 255         per java.lang.reflect.AccessibleObject are not overridden. */
 256     public Constructor<?> newConstructor(Class<?> declaringClass,
 257                                          Class<?>[] parameterTypes,
 258                                          Class<?>[] checkedExceptions,
 259                                          int modifiers,
 260                                          int slot,
 261                                          String signature,
 262                                          byte[] annotations,
 263                                          byte[] parameterAnnotations)
 264     {
 265         return langReflectAccess().newConstructor(declaringClass,
 266                                                   parameterTypes,
 267                                                   checkedExceptions,
 268                                                   modifiers,
 269                                                   slot,
 270                                                   signature,
 271                                                   annotations,
 272                                                   parameterAnnotations);
 273     }
 274 
 275     /** Gets the MethodAccessor object for a java.lang.reflect.Method */
 276     public MethodAccessor getMethodAccessor(Method m) {
 277         return langReflectAccess().getMethodAccessor(m);
 278     }
 279 
 280     /** Sets the MethodAccessor object for a java.lang.reflect.Method */
 281     public void setMethodAccessor(Method m, MethodAccessor accessor) {
 282         langReflectAccess().setMethodAccessor(m, accessor);
 283     }
 284 
 285     /** Gets the ConstructorAccessor object for a
 286         java.lang.reflect.Constructor */
 287     public ConstructorAccessor getConstructorAccessor(Constructor<?> c) {
 288         return langReflectAccess().getConstructorAccessor(c);
 289     }
 290 
 291     /** Sets the ConstructorAccessor object for a
 292         java.lang.reflect.Constructor */
 293     public void setConstructorAccessor(Constructor<?> c,
 294                                        ConstructorAccessor accessor)
 295     {
 296         langReflectAccess().setConstructorAccessor(c, accessor);
 297     }
 298 
 299     /** Makes a copy of the passed method. The returned method is a
 300         "child" of the passed one; see the comments in Method.java for
 301         details. */
 302     public Method copyMethod(Method arg) {
 303         return langReflectAccess().copyMethod(arg);
 304     }
 305 
 306     /** Makes a copy of the passed method. The returned method is NOT
 307      * a "child" but a "sibling" of the Method in arg. Should only be
 308      * used on non-root methods. */
 309     public Method leafCopyMethod(Method arg) {
 310         return langReflectAccess().leafCopyMethod(arg);
 311     }
 312 
 313 
 314     /** Makes a copy of the passed field. The returned field is a
 315         "child" of the passed one; see the comments in Field.java for
 316         details. */
 317     public Field copyField(Field arg) {
 318         return langReflectAccess().copyField(arg);
 319     }
 320 
 321     /** Makes a copy of the passed constructor. The returned
 322         constructor is a "child" of the passed one; see the comments
 323         in Constructor.java for details. */
 324     public <T> Constructor<T> copyConstructor(Constructor<T> arg) {
 325         return langReflectAccess().copyConstructor(arg);
 326     }
 327 
 328     /** Gets the byte[] that encodes TypeAnnotations on an executable.
 329      */
 330     public byte[] getExecutableTypeAnnotationBytes(Executable ex) {
 331         return langReflectAccess().getExecutableTypeAnnotationBytes(ex);
 332     }
 333 
 334     public Class<?>[] getExecutableSharedParameterTypes(Executable ex) {
 335         return langReflectAccess().getExecutableSharedParameterTypes(ex);
 336     }
 337 
 338     //--------------------------------------------------------------------------
 339     //
 340     // Routines used by serialization
 341     //
 342     //
 343 
 344     public Constructor<?> newConstructorForSerialization
 345         (Class<?> classToInstantiate, Constructor<?> constructorToCall)
 346     {
 347         // Fast path
 348         if (constructorToCall.getDeclaringClass() == classToInstantiate) {
 349             return constructorToCall;
 350         }
 351 
 352         ConstructorAccessor acc = new MethodAccessorGenerator().
 353             generateSerializationConstructor(classToInstantiate,
 354                                              constructorToCall.getParameterTypes(),
 355                                              constructorToCall.getExceptionTypes(),
 356                                              constructorToCall.getModifiers(),
 357                                              constructorToCall.getDeclaringClass());
 358         Constructor<?> c = newConstructor(constructorToCall.getDeclaringClass(),
 359                                           constructorToCall.getParameterTypes(),
 360                                           constructorToCall.getExceptionTypes(),
 361                                           constructorToCall.getModifiers(),
 362                                           langReflectAccess().
 363                                           getConstructorSlot(constructorToCall),
 364                                           langReflectAccess().
 365                                           getConstructorSignature(constructorToCall),
 366                                           langReflectAccess().
 367                                           getConstructorAnnotations(constructorToCall),
 368                                           langReflectAccess().
 369                                           getConstructorParameterAnnotations(constructorToCall));
 370         setConstructorAccessor(c, acc);
 371         return c;
 372     }
 373 
 374     //--------------------------------------------------------------------------
 375     //
 376     // Internals only below this point
 377     //
 378 
 379     static int inflationThreshold() {
 380         return inflationThreshold;
 381     }
 382 
 383     /** We have to defer full initialization of this class until after
 384         the static initializer is run since java.lang.reflect.Method's
 385         static initializer (more properly, that for
 386         java.lang.reflect.AccessibleObject) causes this class's to be
 387         run, before the system properties are set up. */
 388     private static void checkInitted() {
 389         if (initted) return;
 390 
 391         // Tests to ensure the system properties table is fully
 392         // initialized. This is needed because reflection code is
 393         // called very early in the initialization process (before
 394         // command-line arguments have been parsed and therefore
 395         // these user-settable properties installed.) We assume that
 396         // if System.out is non-null then the System class has been
 397         // fully initialized and that the bulk of the startup code
 398         // has been run.
 399 
 400         if (System.out == null) {
 401             // java.lang.System not yet fully initialized
 402             return;
 403         }
 404 
 405         Properties props = GetPropertyAction.privilegedGetProperties();
 406         String val = props.getProperty("sun.reflect.noInflation");
 407         if (val != null && val.equals("true")) {
 408             noInflation = true;
 409         }
 410 
 411         val = props.getProperty("sun.reflect.inflationThreshold");
 412         if (val != null) {
 413             try {
 414                 inflationThreshold = Integer.parseInt(val);
 415             } catch (NumberFormatException e) {
 416                 throw new RuntimeException("Unable to parse property sun.reflect.inflationThreshold", e);
 417             }
 418         }
 419 
 420         initted = true;
 421     }
 422 
 423     private static LangReflectAccess langReflectAccess() {
 424         if (langReflectAccess == null) {
 425             // Call a static method to get class java.lang.reflect.Modifier
 426             // initialized. Its static initializer will cause
 427             // setLangReflectAccess() to be called from the context of the
 428             // java.lang.reflect package.
 429             Modifier.isPublic(Modifier.PUBLIC);
 430         }
 431         return langReflectAccess;
 432     }
 433 }