29 import jdk.internal.access.SharedSecrets;
30 import jdk.internal.constant.ClassOrInterfaceDescImpl;
31 import jdk.internal.misc.CDS;
32 import jdk.internal.util.ClassFileDumper;
33 import sun.invoke.util.VerifyAccess;
34
35 import java.io.Serializable;
36 import java.lang.classfile.ClassBuilder;
37 import java.lang.classfile.ClassFile;
38 import java.lang.classfile.CodeBuilder;
39 import java.lang.classfile.MethodBuilder;
40 import java.lang.classfile.Opcode;
41 import java.lang.classfile.TypeKind;
42 import java.lang.constant.ClassDesc;
43 import java.lang.constant.MethodTypeDesc;
44 import java.lang.reflect.Modifier;
45 import java.util.LinkedHashSet;
46 import java.util.List;
47 import java.util.Set;
48 import java.util.function.Consumer;
49
50 import static java.lang.classfile.ClassFile.*;
51 import java.lang.classfile.attribute.ExceptionsAttribute;
52 import java.lang.classfile.constantpool.ClassEntry;
53 import java.lang.classfile.constantpool.ConstantPoolBuilder;
54
55 import static java.lang.constant.ConstantDescs.*;
56 import static java.lang.invoke.MethodHandleNatives.Constants.NESTMATE_CLASS;
57 import static java.lang.invoke.MethodHandleNatives.Constants.STRONG_LOADER_LINK;
58 import jdk.internal.constant.ConstantUtils;
59 import jdk.internal.constant.MethodTypeDescImpl;
60 import jdk.internal.vm.annotation.Stable;
61 import sun.invoke.util.Wrapper;
62
63 /**
64 * Lambda metafactory implementation which dynamically creates an
65 * inner-class-like class per lambda callsite.
66 *
67 * @see LambdaMetafactory
68 */
69 /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory {
70 private static final String LAMBDA_INSTANCE_FIELD = "LAMBDA_INSTANCE$";
71 private static final @Stable String[] ARG_NAME_CACHE = {"arg$1", "arg$2", "arg$3", "arg$4", "arg$5", "arg$6", "arg$7", "arg$8"};
72 private static final ClassDesc[] EMPTY_CLASSDESC_ARRAY = ConstantUtils.EMPTY_CLASSDESC;
73
74 private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
75
76 // For dumping generated classes to disk, for debugging purposes
77 private static final ClassFileDumper lambdaProxyClassFileDumper;
118 * which the lambda or method reference is being
119 * converted, represented as a String.
120 * @param interfaceMethodType Type of the method in the functional interface to
121 * which the lambda or method reference is being
122 * converted, represented as a MethodType.
123 * @param implementation The implementation method which should be called (with
124 * suitable adaptation of argument types, return types,
125 * and adjustment for captured arguments) when methods of
126 * the resulting functional interface instance are invoked.
127 * @param dynamicMethodType The signature of the primary functional
128 * interface method after type variables are
129 * substituted with their instantiation from
130 * the capture site
131 * @param isSerializable Should the lambda be made serializable? If set,
132 * either the target type or one of the additional SAM
133 * types must extend {@code Serializable}.
134 * @param altInterfaces Additional interfaces which the lambda object
135 * should implement.
136 * @param altMethods Method types for additional signatures to be
137 * implemented by invoking the implementation method
138 * @throws LambdaConversionException If any of the meta-factory protocol
139 * invariants are violated
140 */
141 public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
142 MethodType factoryType,
143 String interfaceMethodName,
144 MethodType interfaceMethodType,
145 MethodHandle implementation,
146 MethodType dynamicMethodType,
147 boolean isSerializable,
148 Class<?>[] altInterfaces,
149 MethodType[] altMethods)
150 throws LambdaConversionException {
151 super(caller, factoryType, interfaceMethodName, interfaceMethodType,
152 implementation, dynamicMethodType,
153 isSerializable, altInterfaces, altMethods);
154 implMethodClassDesc = implClassDesc(implClass);
155 implMethodName = implInfo.getName();
156 implMethodDesc = methodDesc(implInfo.getMethodType());
157 constructorType = factoryType.changeReturnType(Void.TYPE);
158 lambdaClassName = lambdaClassName(targetClass);
159 lambdaClassEntry = pool.classEntry(ConstantUtils.internalNameToDesc(lambdaClassName));
160 // If the target class invokes a protected method inherited from a
161 // superclass in a different package, or does 'invokespecial', the
162 // lambda class has no access to the resolved method, or does
163 // 'invokestatic' on a hidden class which cannot be resolved by name.
164 // Instead, we need to pass the live implementation method handle to
165 // the proxy class to invoke directly. (javac prefers to avoid this
166 // situation by generating bridges in the target class)
167 useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
168 !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
169 implKind == MethodHandleInfo.REF_invokeSpecial ||
170 implKind == MethodHandleInfo.REF_invokeStatic && implClass.isHidden();
171 int parameterCount = factoryType.parameterCount();
172 ClassDesc[] argDescs;
173 MethodTypeDesc constructorTypeDesc;
294 * @throws LambdaConversionException If properly formed functional interface
295 * is not found
296 */
297 private Class<?> generateInnerClass() throws LambdaConversionException {
298 List<ClassDesc> interfaces;
299 ClassDesc interfaceDesc = classDesc(interfaceClass);
300 boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
301 if (altInterfaces.length == 0) {
302 interfaces = List.of(interfaceDesc);
303 } else {
304 // Assure no duplicate interfaces (ClassFormatError)
305 Set<ClassDesc> itfs = LinkedHashSet.newLinkedHashSet(altInterfaces.length + 1);
306 itfs.add(interfaceDesc);
307 for (Class<?> i : altInterfaces) {
308 itfs.add(classDesc(i));
309 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
310 }
311 interfaces = List.copyOf(itfs);
312 }
313 final boolean finalAccidentallySerializable = accidentallySerializable;
314 final byte[] classBytes = ClassFile.of().build(lambdaClassEntry, pool, new Consumer<ClassBuilder>() {
315 @Override
316 public void accept(ClassBuilder clb) {
317 clb.withFlags(ACC_SUPER | ACC_FINAL | ACC_SYNTHETIC)
318 .withInterfaceSymbols(interfaces);
319 // All Classes in the BSM argument method types are loaded; no need for LoadableDescriptors
320
321 // Generate final fields to be filled in by constructor
322 for (int i = 0; i < argDescs.length; i++) {
323 clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
324 }
325
326 generateConstructor(clb);
327
328 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
329 generateClassInitializer(clb);
330 }
331
332 // Forward the SAM method
333 clb.withMethodBody(interfaceMethodName,
334 methodDesc(interfaceMethodType),
335 ACC_PUBLIC,
336 forwardingMethod(interfaceMethodType));
337
338 // Forward the bridges
339 if (altMethods != null) {
340 for (MethodType mt : altMethods) {
341 clb.withMethodBody(interfaceMethodName,
342 methodDesc(mt),
343 ACC_PUBLIC | ACC_BRIDGE,
344 forwardingMethod(mt));
345 }
346 }
347
348 if (isSerializable)
349 generateSerializationFriendlyMethods(clb);
350 else if (finalAccidentallySerializable)
351 generateSerializationHostileMethods(clb);
352 }
353 });
354
355 // Define the generated class in this VM.
356
357 try {
358 // This class is linked at the indy callsite; so define a hidden nestmate.
359 // Redefinition or retransformation of the caller can cause lambda call
360 // sites to be linked again, generating additional proxy classes.
361 // If the caller or a superclass has been redefined, allow newly generated
362 // proxies to unload independently of the defining class loader.
363 int flags = NESTMATE_CLASS;
364 if (!JLA.hasBeenRedefined(caller.lookupClass())) {
365 flags |= STRONG_LOADER_LINK;
366 }
367 var classdata = useImplMethodHandle? implementation : null;
368 return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, flags)
369 .defineClass(!disableEagerInitialization, classdata);
370
371 } catch (Throwable t) {
372 throw new InternalError(t);
373 }
374 }
375
376 /**
377 * Generate a static field and a static initializer that sets this field to an instance of the lambda
378 */
379 private void generateClassInitializer(ClassBuilder clb) {
380 ClassDesc lambdaTypeDescriptor = classDesc(factoryType.returnType());
381
382 // Generate the static final field that holds the lambda singleton
383 clb.withField(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
384
385 // Instantiate the lambda and store it to the static final field
386 clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, new Consumer<>() {
387 @Override
388 public void accept(CodeBuilder cob) {
389 assert factoryType.parameterCount() == 0;
500 clb.withMethod(SerializationSupport.NAME_METHOD_WRITE_OBJECT, SerializationSupport.MTD_void_ObjectOutputStream,
501 ACC_PRIVATE + ACC_FINAL, hostileMethod);
502 clb.withMethod(SerializationSupport.NAME_METHOD_READ_OBJECT, SerializationSupport.MTD_void_ObjectInputStream,
503 ACC_PRIVATE + ACC_FINAL, hostileMethod);
504 }
505
506 /**
507 * This method generates a method body which calls the lambda implementation
508 * method, converting arguments, as needed.
509 */
510 Consumer<CodeBuilder> forwardingMethod(MethodType methodType) {
511 return new Consumer<>() {
512 @Override
513 public void accept(CodeBuilder cob) {
514 if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
515 cob.new_(implMethodClassDesc)
516 .dup();
517 }
518 if (useImplMethodHandle) {
519 ConstantPoolBuilder cp = cob.constantPool();
520 cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA), List.of()),
521 cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
522 }
523 for (int i = 0; i < argDescs.length; i++) {
524 cob.aload(0)
525 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
526 }
527
528 convertArgumentTypes(cob, methodType);
529
530 if (useImplMethodHandle) {
531 MethodType mtype = implInfo.getMethodType();
532 if (implKind != MethodHandleInfo.REF_invokeStatic) {
533 mtype = mtype.insertParameterTypes(0, implClass);
534 }
535 cob.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(mtype));
536 } else {
537 // Invoke the method we want to forward to
538 cob.invoke(invocationOpcode(), implMethodClassDesc, implMethodName, implMethodDesc, implClass.isInterface());
539 }
540 // Convert the return value (if any) and return it
|
29 import jdk.internal.access.SharedSecrets;
30 import jdk.internal.constant.ClassOrInterfaceDescImpl;
31 import jdk.internal.misc.CDS;
32 import jdk.internal.util.ClassFileDumper;
33 import sun.invoke.util.VerifyAccess;
34
35 import java.io.Serializable;
36 import java.lang.classfile.ClassBuilder;
37 import java.lang.classfile.ClassFile;
38 import java.lang.classfile.CodeBuilder;
39 import java.lang.classfile.MethodBuilder;
40 import java.lang.classfile.Opcode;
41 import java.lang.classfile.TypeKind;
42 import java.lang.constant.ClassDesc;
43 import java.lang.constant.MethodTypeDesc;
44 import java.lang.reflect.Modifier;
45 import java.util.LinkedHashSet;
46 import java.util.List;
47 import java.util.Set;
48 import java.util.function.Consumer;
49 import java.util.function.Function;
50
51 import static java.lang.classfile.ClassFile.*;
52 import java.lang.classfile.attribute.ExceptionsAttribute;
53 import java.lang.classfile.constantpool.ClassEntry;
54 import java.lang.classfile.constantpool.ConstantPoolBuilder;
55
56 import static java.lang.constant.ConstantDescs.*;
57 import static java.lang.invoke.MethodHandleNatives.Constants.NESTMATE_CLASS;
58 import static java.lang.invoke.MethodHandleNatives.Constants.STRONG_LOADER_LINK;
59 import java.util.ArrayList;
60 import jdk.internal.constant.ConstantUtils;
61 import jdk.internal.constant.MethodTypeDescImpl;
62 import jdk.internal.vm.annotation.Stable;
63 import sun.invoke.util.Wrapper;
64
65 /**
66 * Lambda metafactory implementation which dynamically creates an
67 * inner-class-like class per lambda callsite.
68 *
69 * @see LambdaMetafactory
70 */
71 /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory {
72 private static final String LAMBDA_INSTANCE_FIELD = "LAMBDA_INSTANCE$";
73 private static final @Stable String[] ARG_NAME_CACHE = {"arg$1", "arg$2", "arg$3", "arg$4", "arg$5", "arg$6", "arg$7", "arg$8"};
74 private static final ClassDesc[] EMPTY_CLASSDESC_ARRAY = ConstantUtils.EMPTY_CLASSDESC;
75
76 private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
77
78 // For dumping generated classes to disk, for debugging purposes
79 private static final ClassFileDumper lambdaProxyClassFileDumper;
120 * which the lambda or method reference is being
121 * converted, represented as a String.
122 * @param interfaceMethodType Type of the method in the functional interface to
123 * which the lambda or method reference is being
124 * converted, represented as a MethodType.
125 * @param implementation The implementation method which should be called (with
126 * suitable adaptation of argument types, return types,
127 * and adjustment for captured arguments) when methods of
128 * the resulting functional interface instance are invoked.
129 * @param dynamicMethodType The signature of the primary functional
130 * interface method after type variables are
131 * substituted with their instantiation from
132 * the capture site
133 * @param isSerializable Should the lambda be made serializable? If set,
134 * either the target type or one of the additional SAM
135 * types must extend {@code Serializable}.
136 * @param altInterfaces Additional interfaces which the lambda object
137 * should implement.
138 * @param altMethods Method types for additional signatures to be
139 * implemented by invoking the implementation method
140 * @param finisher Function called at the end of the lambda class build process
141 * that returns an additional object to append to the class data,
142 * may be (@code null}, may return {@code null}.
143 * @throws LambdaConversionException If any of the meta-factory protocol
144 * invariants are violated
145 */
146 public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
147 MethodType factoryType,
148 String interfaceMethodName,
149 MethodType interfaceMethodType,
150 MethodHandle implementation,
151 MethodType dynamicMethodType,
152 boolean isSerializable,
153 Class<?>[] altInterfaces,
154 MethodType[] altMethods,
155 Function<ClassBuilder, Object> finisher)
156 throws LambdaConversionException {
157 super(caller, factoryType, interfaceMethodName, interfaceMethodType,
158 implementation, dynamicMethodType,
159 isSerializable, altInterfaces, altMethods, finisher);
160 implMethodClassDesc = implClassDesc(implClass);
161 implMethodName = implInfo.getName();
162 implMethodDesc = methodDesc(implInfo.getMethodType());
163 constructorType = factoryType.changeReturnType(Void.TYPE);
164 lambdaClassName = lambdaClassName(targetClass);
165 lambdaClassEntry = pool.classEntry(ConstantUtils.internalNameToDesc(lambdaClassName));
166 // If the target class invokes a protected method inherited from a
167 // superclass in a different package, or does 'invokespecial', the
168 // lambda class has no access to the resolved method, or does
169 // 'invokestatic' on a hidden class which cannot be resolved by name.
170 // Instead, we need to pass the live implementation method handle to
171 // the proxy class to invoke directly. (javac prefers to avoid this
172 // situation by generating bridges in the target class)
173 useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
174 !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
175 implKind == MethodHandleInfo.REF_invokeSpecial ||
176 implKind == MethodHandleInfo.REF_invokeStatic && implClass.isHidden();
177 int parameterCount = factoryType.parameterCount();
178 ClassDesc[] argDescs;
179 MethodTypeDesc constructorTypeDesc;
300 * @throws LambdaConversionException If properly formed functional interface
301 * is not found
302 */
303 private Class<?> generateInnerClass() throws LambdaConversionException {
304 List<ClassDesc> interfaces;
305 ClassDesc interfaceDesc = classDesc(interfaceClass);
306 boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
307 if (altInterfaces.length == 0) {
308 interfaces = List.of(interfaceDesc);
309 } else {
310 // Assure no duplicate interfaces (ClassFormatError)
311 Set<ClassDesc> itfs = LinkedHashSet.newLinkedHashSet(altInterfaces.length + 1);
312 itfs.add(interfaceDesc);
313 for (Class<?> i : altInterfaces) {
314 itfs.add(classDesc(i));
315 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
316 }
317 interfaces = List.copyOf(itfs);
318 }
319 final boolean finalAccidentallySerializable = accidentallySerializable;
320 final Object[] additionalClassDataHolder = new Object[1];
321 final byte[] classBytes = ClassFile.of().build(lambdaClassEntry, pool, new Consumer<ClassBuilder>() {
322 @Override
323 public void accept(ClassBuilder clb) {
324 clb.withFlags(ACC_SUPER | ACC_FINAL | ACC_SYNTHETIC)
325 .withInterfaceSymbols(interfaces);
326 // All Classes in the BSM argument method types are loaded; no need for LoadableDescriptors
327
328 // Generate final fields to be filled in by constructor
329 for (int i = 0; i < argDescs.length; i++) {
330 clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
331 }
332
333 generateConstructor(clb);
334
335 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
336 generateClassInitializer(clb);
337 }
338
339 // Forward the SAM method
340 clb.withMethodBody(interfaceMethodName,
341 methodDesc(interfaceMethodType),
342 ACC_PUBLIC,
343 forwardingMethod(interfaceMethodType));
344
345 // Forward the bridges
346 if (altMethods != null) {
347 for (MethodType mt : altMethods) {
348 clb.withMethodBody(interfaceMethodName,
349 methodDesc(mt),
350 ACC_PUBLIC | ACC_BRIDGE,
351 forwardingMethod(mt));
352 }
353 }
354
355 if (isSerializable)
356 generateSerializationFriendlyMethods(clb);
357 else if (finalAccidentallySerializable)
358 generateSerializationHostileMethods(clb);
359
360 if (finisher != null) {
361 additionalClassDataHolder[0] = finisher.apply(clb);
362 }
363 }
364 });
365
366 // Define the generated class in this VM.
367
368 try {
369 // This class is linked at the indy callsite; so define a hidden nestmate.
370 // Redefinition or retransformation of the caller can cause lambda call
371 // sites to be linked again, generating additional proxy classes.
372 // If the caller or a superclass has been redefined, allow newly generated
373 // proxies to unload independently of the defining class loader.
374 int flags = NESTMATE_CLASS;
375 if (!JLA.hasBeenRedefined(caller.lookupClass())) {
376 flags |= STRONG_LOADER_LINK;
377 }
378 var additionalClassData = additionalClassDataHolder[0];
379 var classdata = additionalClassData == null
380 ? useImplMethodHandle ? List.of(implementation) : null
381 : useImplMethodHandle ? List.of(implementation, additionalClassData) : List.of(additionalClassData);
382 return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, flags)
383 .defineClass(!disableEagerInitialization, classdata);
384
385 } catch (Throwable t) {
386 throw new InternalError(t);
387 }
388 }
389
390 /**
391 * Generate a static field and a static initializer that sets this field to an instance of the lambda
392 */
393 private void generateClassInitializer(ClassBuilder clb) {
394 ClassDesc lambdaTypeDescriptor = classDesc(factoryType.returnType());
395
396 // Generate the static final field that holds the lambda singleton
397 clb.withField(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
398
399 // Instantiate the lambda and store it to the static final field
400 clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, new Consumer<>() {
401 @Override
402 public void accept(CodeBuilder cob) {
403 assert factoryType.parameterCount() == 0;
514 clb.withMethod(SerializationSupport.NAME_METHOD_WRITE_OBJECT, SerializationSupport.MTD_void_ObjectOutputStream,
515 ACC_PRIVATE + ACC_FINAL, hostileMethod);
516 clb.withMethod(SerializationSupport.NAME_METHOD_READ_OBJECT, SerializationSupport.MTD_void_ObjectInputStream,
517 ACC_PRIVATE + ACC_FINAL, hostileMethod);
518 }
519
520 /**
521 * This method generates a method body which calls the lambda implementation
522 * method, converting arguments, as needed.
523 */
524 Consumer<CodeBuilder> forwardingMethod(MethodType methodType) {
525 return new Consumer<>() {
526 @Override
527 public void accept(CodeBuilder cob) {
528 if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
529 cob.new_(implMethodClassDesc)
530 .dup();
531 }
532 if (useImplMethodHandle) {
533 ConstantPoolBuilder cp = cob.constantPool();
534 cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA_AT), List.of(cp.intEntry(0))),
535 cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
536 }
537 for (int i = 0; i < argDescs.length; i++) {
538 cob.aload(0)
539 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
540 }
541
542 convertArgumentTypes(cob, methodType);
543
544 if (useImplMethodHandle) {
545 MethodType mtype = implInfo.getMethodType();
546 if (implKind != MethodHandleInfo.REF_invokeStatic) {
547 mtype = mtype.insertParameterTypes(0, implClass);
548 }
549 cob.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(mtype));
550 } else {
551 // Invoke the method we want to forward to
552 cob.invoke(invocationOpcode(), implMethodClassDesc, implMethodName, implMethodDesc, implClass.isInterface());
553 }
554 // Convert the return value (if any) and return it
|