< prev index next >

src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java

Print this page

  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.invoke;
 27 
 28 import jdk.internal.misc.CDS;
 29 import jdk.internal.misc.VM;
 30 import jdk.internal.org.objectweb.asm.*;
 31 import sun.invoke.util.BytecodeDescriptor;
 32 import sun.invoke.util.VerifyAccess;
 33 import sun.security.action.GetPropertyAction;
 34 import sun.security.action.GetBooleanAction;
 35 
 36 import java.io.FilePermission;
 37 import java.io.Serializable;
 38 import java.lang.constant.ConstantDescs;
 39 import java.lang.invoke.MethodHandles.Lookup;
 40 import java.lang.reflect.Constructor;
 41 import java.lang.reflect.Modifier;
 42 import java.security.AccessController;
 43 import java.security.PrivilegedAction;
 44 import java.util.LinkedHashSet;
 45 import java.util.concurrent.atomic.AtomicInteger;
 46 import java.util.PropertyPermission;
 47 import java.util.Set;
 48 

 49 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.NESTMATE;
 50 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.STRONG;

 51 import static jdk.internal.org.objectweb.asm.Opcodes.*;
 52 
 53 /**
 54  * Lambda metafactory implementation which dynamically creates an
 55  * inner-class-like class per lambda callsite.
 56  *
 57  * @see LambdaMetafactory
 58  */
 59 /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory {
 60     private static final int CLASSFILE_VERSION = VM.classFileVersion();
 61     private static final String METHOD_DESCRIPTOR_VOID = Type.getMethodDescriptor(Type.VOID_TYPE);
 62     private static final String JAVA_LANG_OBJECT = "java/lang/Object";
 63     private static final String NAME_CTOR = "<init>";
 64     private static final String LAMBDA_INSTANCE_FIELD = "LAMBDA_INSTANCE$";
 65 
 66     //Serialization support
 67     private static final String NAME_SERIALIZED_LAMBDA = "java/lang/invoke/SerializedLambda";
 68     private static final String NAME_NOT_SERIALIZABLE_EXCEPTION = "java/io/NotSerializableException";
 69     private static final String DESCR_METHOD_WRITE_REPLACE = "()Ljava/lang/Object;";
 70     private static final String DESCR_METHOD_WRITE_OBJECT = "(Ljava/io/ObjectOutputStream;)V";
 71     private static final String DESCR_METHOD_READ_OBJECT = "(Ljava/io/ObjectInputStream;)V";
 72 
 73     private static final String NAME_METHOD_WRITE_REPLACE = "writeReplace";
 74     private static final String NAME_METHOD_READ_OBJECT = "readObject";
 75     private static final String NAME_METHOD_WRITE_OBJECT = "writeObject";
 76 
 77     private static final String DESCR_CLASS = "Ljava/lang/Class;";
 78     private static final String DESCR_STRING = "Ljava/lang/String;";
 79     private static final String DESCR_OBJECT = "Ljava/lang/Object;";
 80     private static final String DESCR_CTOR_SERIALIZED_LAMBDA

 89     // Used to ensure that each spun class name is unique
 90     private static final AtomicInteger counter = new AtomicInteger();
 91 
 92     // For dumping generated classes to disk, for debugging purposes
 93     private static final ProxyClassesDumper dumper;
 94 
 95     private static final boolean disableEagerInitialization;
 96 
 97     // condy to load implMethod from class data
 98     private static final ConstantDynamic implMethodCondy;
 99 
100     static {
101         final String dumpProxyClassesKey = "jdk.internal.lambda.dumpProxyClasses";
102         String dumpPath = GetPropertyAction.privilegedGetProperty(dumpProxyClassesKey);
103         dumper = (null == dumpPath) ? null : ProxyClassesDumper.getInstance(dumpPath);
104 
105         final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
106         disableEagerInitialization = GetBooleanAction.privilegedGetProperty(disableEagerInitializationKey);
107 
108         // condy to load implMethod from class data
109         MethodType classDataMType = MethodType.methodType(Object.class, MethodHandles.Lookup.class, String.class, Class.class);
110         Handle classDataBsm = new Handle(H_INVOKESTATIC, Type.getInternalName(MethodHandles.class), "classData",
111                                          classDataMType.descriptorString(), false);
112         implMethodCondy = new ConstantDynamic(ConstantDescs.DEFAULT_NAME, MethodHandle.class.descriptorString(), classDataBsm);
113     }
114 
115     // See context values in AbstractValidatingLambdaMetafactory
116     private final String implMethodClassName;        // Name of type containing implementation "CC"
117     private final String implMethodName;             // Name of implementation method "impl"
118     private final String implMethodDesc;             // Type descriptor for implementation methods "(I)Ljava/lang/String;"
119     private final MethodType constructorType;        // Generated class constructor type "(CC)void"
120     private final ClassWriter cw;                    // ASM class writer
121     private final String[] argNames;                 // Generated names for the constructor arguments
122     private final String[] argDescs;                 // Type descriptors for the constructor arguments
123     private final String lambdaClassName;            // Generated name for the generated class "X$$Lambda$1"
124     private final boolean useImplMethodHandle;       // use MethodHandle invocation instead of symbolic bytecode invocation
125 
126     /**
127      * General meta-factory constructor, supporting both standard cases and
128      * allowing for uncommon options such as serialization or bridging.
129      *

210             // use the original class name
211             name = name.replace('/', '_');
212         }
213         return name.replace('.', '/') + "$$Lambda$" + counter.incrementAndGet();
214     }
215 
216     /**
217      * Build the CallSite. Generate a class file which implements the functional
218      * interface, define the class, if there are no parameters create an instance
219      * of the class which the CallSite will return, otherwise, generate handles
220      * which will call the class' constructor.
221      *
222      * @return a CallSite, which, when invoked, will return an instance of the
223      * functional interface
224      * @throws LambdaConversionException If properly formed functional interface
225      * is not found
226      */
227     @Override
228     CallSite buildCallSite() throws LambdaConversionException {
229         final Class<?> innerClass = spinInnerClass();
230         if (factoryType.parameterCount() == 0) {
231             // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance,
232             // unless we've suppressed eager initialization
233             if (disableEagerInitialization) {
234                 try {
235                     return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
236                             factoryType.returnType()));
237                 } catch (ReflectiveOperationException e) {
238                     throw new LambdaConversionException(
239                             "Exception finding " +  LAMBDA_INSTANCE_FIELD + " static field", e);
240                 }
241             } else {
242                 @SuppressWarnings("removal")
243                 final Constructor<?>[] ctrs = AccessController.doPrivileged(
244                         new PrivilegedAction<>() {
245                             @Override
246                             public Constructor<?>[] run() {
247                                 Constructor<?>[] ctrs = innerClass.getDeclaredConstructors();
248                                 if (ctrs.length == 1) {
249                                     // The lambda implementing inner class constructor is private, set
250                                     // it accessible (by us) before creating the constant sole instance
251                                     ctrs[0].setAccessible(true);
252                                 }
253                                 return ctrs;
254                             }
255                         });
256                 if (ctrs.length != 1) {
257                     throw new LambdaConversionException("Expected one lambda constructor for "
258                             + innerClass.getCanonicalName() + ", got " + ctrs.length);
259                 }
260 
261                 try {
262                     Object inst = ctrs[0].newInstance();
263                     return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
264                 } catch (ReflectiveOperationException e) {
265                     throw new LambdaConversionException("Exception instantiating lambda object", e);
266                 }
267             }
268         } else {
269             try {
270                 MethodHandle mh = caller.findConstructor(innerClass, constructorType);
271                 return new ConstantCallSite(mh.asType(factoryType));






272             } catch (ReflectiveOperationException e) {
273                 throw new LambdaConversionException("Exception finding constructor", e);


274             }
275         }
276     }
277 
278     /**
279      * Spins the lambda proxy class.
280      *
281      * This first checks if a lambda proxy class can be loaded from CDS archive.
282      * Otherwise, generate the lambda proxy class. If CDS dumping is enabled, it
283      * registers the lambda proxy class for including into the CDS archive.
284      */
285     private Class<?> spinInnerClass() throws LambdaConversionException {
286         // CDS does not handle disableEagerInitialization.
287         if (!disableEagerInitialization) {
288             // include lambda proxy class in CDS archive at dump time
289             if (CDS.isDumpingArchive()) {
290                 Class<?> innerClass = generateInnerClass();
291                 LambdaProxyClassArchive.register(targetClass,
292                                                  interfaceMethodName,
293                                                  factoryType,

  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.invoke;
 27 
 28 import jdk.internal.misc.CDS;

 29 import jdk.internal.org.objectweb.asm.*;
 30 import sun.invoke.util.BytecodeDescriptor;
 31 import sun.invoke.util.VerifyAccess;
 32 import sun.security.action.GetPropertyAction;
 33 import sun.security.action.GetBooleanAction;
 34 
 35 import java.io.FilePermission;
 36 import java.io.Serializable;
 37 import java.lang.constant.ConstantDescs;
 38 import java.lang.invoke.MethodHandles.Lookup;

 39 import java.lang.reflect.Modifier;
 40 import java.security.AccessController;
 41 import java.security.PrivilegedAction;
 42 import java.util.LinkedHashSet;
 43 import java.util.concurrent.atomic.AtomicInteger;
 44 import java.util.PropertyPermission;
 45 import java.util.Set;
 46 
 47 import static java.lang.invoke.MethodHandleStatics.CLASSFILE_VERSION;
 48 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.NESTMATE;
 49 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.STRONG;
 50 import static java.lang.invoke.MethodType.methodType;
 51 import static jdk.internal.org.objectweb.asm.Opcodes.*;
 52 
 53 /**
 54  * Lambda metafactory implementation which dynamically creates an
 55  * inner-class-like class per lambda callsite.
 56  *
 57  * @see LambdaMetafactory
 58  */
 59 /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory {

 60     private static final String METHOD_DESCRIPTOR_VOID = Type.getMethodDescriptor(Type.VOID_TYPE);
 61     private static final String JAVA_LANG_OBJECT = "java/lang/Object";
 62     private static final String NAME_CTOR = "<init>";
 63     private static final String LAMBDA_INSTANCE_FIELD = "LAMBDA_INSTANCE$";
 64 
 65     //Serialization support
 66     private static final String NAME_SERIALIZED_LAMBDA = "java/lang/invoke/SerializedLambda";
 67     private static final String NAME_NOT_SERIALIZABLE_EXCEPTION = "java/io/NotSerializableException";
 68     private static final String DESCR_METHOD_WRITE_REPLACE = "()Ljava/lang/Object;";
 69     private static final String DESCR_METHOD_WRITE_OBJECT = "(Ljava/io/ObjectOutputStream;)V";
 70     private static final String DESCR_METHOD_READ_OBJECT = "(Ljava/io/ObjectInputStream;)V";
 71 
 72     private static final String NAME_METHOD_WRITE_REPLACE = "writeReplace";
 73     private static final String NAME_METHOD_READ_OBJECT = "readObject";
 74     private static final String NAME_METHOD_WRITE_OBJECT = "writeObject";
 75 
 76     private static final String DESCR_CLASS = "Ljava/lang/Class;";
 77     private static final String DESCR_STRING = "Ljava/lang/String;";
 78     private static final String DESCR_OBJECT = "Ljava/lang/Object;";
 79     private static final String DESCR_CTOR_SERIALIZED_LAMBDA

 88     // Used to ensure that each spun class name is unique
 89     private static final AtomicInteger counter = new AtomicInteger();
 90 
 91     // For dumping generated classes to disk, for debugging purposes
 92     private static final ProxyClassesDumper dumper;
 93 
 94     private static final boolean disableEagerInitialization;
 95 
 96     // condy to load implMethod from class data
 97     private static final ConstantDynamic implMethodCondy;
 98 
 99     static {
100         final String dumpProxyClassesKey = "jdk.internal.lambda.dumpProxyClasses";
101         String dumpPath = GetPropertyAction.privilegedGetProperty(dumpProxyClassesKey);
102         dumper = (null == dumpPath) ? null : ProxyClassesDumper.getInstance(dumpPath);
103 
104         final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
105         disableEagerInitialization = GetBooleanAction.privilegedGetProperty(disableEagerInitializationKey);
106 
107         // condy to load implMethod from class data
108         MethodType classDataMType = methodType(Object.class, MethodHandles.Lookup.class, String.class, Class.class);
109         Handle classDataBsm = new Handle(H_INVOKESTATIC, Type.getInternalName(MethodHandles.class), "classData",
110                                          classDataMType.descriptorString(), false);
111         implMethodCondy = new ConstantDynamic(ConstantDescs.DEFAULT_NAME, MethodHandle.class.descriptorString(), classDataBsm);
112     }
113 
114     // See context values in AbstractValidatingLambdaMetafactory
115     private final String implMethodClassName;        // Name of type containing implementation "CC"
116     private final String implMethodName;             // Name of implementation method "impl"
117     private final String implMethodDesc;             // Type descriptor for implementation methods "(I)Ljava/lang/String;"
118     private final MethodType constructorType;        // Generated class constructor type "(CC)void"
119     private final ClassWriter cw;                    // ASM class writer
120     private final String[] argNames;                 // Generated names for the constructor arguments
121     private final String[] argDescs;                 // Type descriptors for the constructor arguments
122     private final String lambdaClassName;            // Generated name for the generated class "X$$Lambda$1"
123     private final boolean useImplMethodHandle;       // use MethodHandle invocation instead of symbolic bytecode invocation
124 
125     /**
126      * General meta-factory constructor, supporting both standard cases and
127      * allowing for uncommon options such as serialization or bridging.
128      *

209             // use the original class name
210             name = name.replace('/', '_');
211         }
212         return name.replace('.', '/') + "$$Lambda$" + counter.incrementAndGet();
213     }
214 
215     /**
216      * Build the CallSite. Generate a class file which implements the functional
217      * interface, define the class, if there are no parameters create an instance
218      * of the class which the CallSite will return, otherwise, generate handles
219      * which will call the class' constructor.
220      *
221      * @return a CallSite, which, when invoked, will return an instance of the
222      * functional interface
223      * @throws LambdaConversionException If properly formed functional interface
224      * is not found
225      */
226     @Override
227     CallSite buildCallSite() throws LambdaConversionException {
228         final Class<?> innerClass = spinInnerClass();
229         if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
230             try {
231                 return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
232                                                                     factoryType.returnType()));
233             } catch (ReflectiveOperationException e) {
234                 throw new LambdaConversionException(
235                         "Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e);






























236             }
237         } else {
238             try {
239                 MethodHandle mh = caller.findConstructor(innerClass, constructorType);
240                 if (factoryType.parameterCount() == 0) {
241                     // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance
242                     Object inst = mh.asType(methodType(Object.class)).invokeExact();
243                     return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
244                 } else {
245                     return new ConstantCallSite(mh.asType(factoryType));
246                 }
247             } catch (ReflectiveOperationException e) {
248                 throw new LambdaConversionException("Exception finding constructor", e);
249             } catch (Throwable e) {
250                 throw new LambdaConversionException("Exception instantiating lambda object", e);
251             }
252         }
253     }
254 
255     /**
256      * Spins the lambda proxy class.
257      *
258      * This first checks if a lambda proxy class can be loaded from CDS archive.
259      * Otherwise, generate the lambda proxy class. If CDS dumping is enabled, it
260      * registers the lambda proxy class for including into the CDS archive.
261      */
262     private Class<?> spinInnerClass() throws LambdaConversionException {
263         // CDS does not handle disableEagerInitialization.
264         if (!disableEagerInitialization) {
265             // include lambda proxy class in CDS archive at dump time
266             if (CDS.isDumpingArchive()) {
267                 Class<?> innerClass = generateInnerClass();
268                 LambdaProxyClassArchive.register(targetClass,
269                                                  interfaceMethodName,
270                                                  factoryType,
< prev index next >