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.invoke;
27
28 import jdk.internal.constant.ClassOrInterfaceDescImpl;
29 import jdk.internal.misc.CDS;
30 import jdk.internal.util.ClassFileDumper;
31 import sun.invoke.util.VerifyAccess;
32
33 import java.io.Serializable;
34 import java.lang.classfile.ClassBuilder;
35 import java.lang.classfile.ClassFile;
36 import java.lang.classfile.CodeBuilder;
37 import java.lang.classfile.MethodBuilder;
38 import java.lang.classfile.Opcode;
39 import java.lang.classfile.TypeKind;
40 import java.lang.constant.ClassDesc;
41 import java.lang.constant.MethodTypeDesc;
42 import java.lang.reflect.Modifier;
43 import java.util.LinkedHashSet;
44 import java.util.List;
45 import java.util.Set;
46 import java.util.function.Consumer;
47
48 import static java.lang.classfile.ClassFile.*;
49 import java.lang.classfile.attribute.ExceptionsAttribute;
50 import java.lang.classfile.constantpool.ClassEntry;
51 import java.lang.classfile.constantpool.ConstantPoolBuilder;
52
53 import static java.lang.constant.ConstantDescs.*;
54 import static java.lang.invoke.MethodHandleNatives.Constants.NESTMATE_CLASS;
55 import static java.lang.invoke.MethodHandleNatives.Constants.STRONG_LOADER_LINK;
56 import jdk.internal.constant.ConstantUtils;
57 import jdk.internal.constant.MethodTypeDescImpl;
58 import jdk.internal.vm.annotation.Stable;
59 import sun.invoke.util.Wrapper;
60
61 /**
62 * Lambda metafactory implementation which dynamically creates an
63 * inner-class-like class per lambda callsite.
64 *
65 * @see LambdaMetafactory
66 */
67 /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory {
68 private static final String LAMBDA_INSTANCE_FIELD = "LAMBDA_INSTANCE$";
69 private static final @Stable String[] ARG_NAME_CACHE = {"arg$1", "arg$2", "arg$3", "arg$4", "arg$5", "arg$6", "arg$7", "arg$8"};
70 private static final ClassDesc[] EMPTY_CLASSDESC_ARRAY = ConstantUtils.EMPTY_CLASSDESC;
71
72 // For dumping generated classes to disk, for debugging purposes
73 private static final ClassFileDumper lambdaProxyClassFileDumper;
74
75 private static final boolean disableEagerInitialization;
76
77 static {
78 // To dump the lambda proxy classes, set this system property:
79 // -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles
80 // or -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles=true
81 final String dumpProxyClassesKey = "jdk.invoke.LambdaMetafactory.dumpProxyClassFiles";
82 lambdaProxyClassFileDumper = ClassFileDumper.getInstance(dumpProxyClassesKey, "DUMP_LAMBDA_PROXY_CLASS_FILES");
83
84 final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
85 disableEagerInitialization = Boolean.getBoolean(disableEagerInitializationKey);
86 }
87
88 // See context values in AbstractValidatingLambdaMetafactory
89 private final ClassDesc implMethodClassDesc; // Name of type containing implementation "CC"
90 private final String implMethodName; // Name of implementation method "impl"
91 private final MethodTypeDesc implMethodDesc; // Type descriptor for implementation methods "(I)Ljava/lang/String;"
92 private final MethodType constructorType; // Generated class constructor type "(CC)void"
93 private final MethodTypeDesc constructorTypeDesc;// Type descriptor for the generated class constructor type "(CC)void"
94 private final ClassDesc[] argDescs; // Type descriptors for the constructor arguments
95 private final String lambdaClassName; // Generated name for the generated class "X$$Lambda$1"
96 private final ConstantPoolBuilder pool = ConstantPoolBuilder.of();
125 * substituted with their instantiation from
126 * the capture site
127 * @param isSerializable Should the lambda be made serializable? If set,
128 * either the target type or one of the additional SAM
129 * types must extend {@code Serializable}.
130 * @param altInterfaces Additional interfaces which the lambda object
131 * should implement.
132 * @param altMethods Method types for additional signatures to be
133 * implemented by invoking the implementation method
134 * @throws LambdaConversionException If any of the meta-factory protocol
135 * invariants are violated
136 */
137 public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
138 MethodType factoryType,
139 String interfaceMethodName,
140 MethodType interfaceMethodType,
141 MethodHandle implementation,
142 MethodType dynamicMethodType,
143 boolean isSerializable,
144 Class<?>[] altInterfaces,
145 MethodType[] altMethods)
146 throws LambdaConversionException {
147 super(caller, factoryType, interfaceMethodName, interfaceMethodType,
148 implementation, dynamicMethodType,
149 isSerializable, altInterfaces, altMethods);
150 implMethodClassDesc = implClassDesc(implClass);
151 implMethodName = implInfo.getName();
152 implMethodDesc = methodDesc(implInfo.getMethodType());
153 constructorType = factoryType.changeReturnType(Void.TYPE);
154 lambdaClassName = lambdaClassName(targetClass);
155 lambdaClassEntry = pool.classEntry(ConstantUtils.internalNameToDesc(lambdaClassName));
156 // If the target class invokes a protected method inherited from a
157 // superclass in a different package, or does 'invokespecial', the
158 // lambda class has no access to the resolved method, or does
159 // 'invokestatic' on a hidden class which cannot be resolved by name.
160 // Instead, we need to pass the live implementation method handle to
161 // the proxy class to invoke directly. (javac prefers to avoid this
162 // situation by generating bridges in the target class)
163 useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
164 !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
165 implKind == MethodHandleInfo.REF_invokeSpecial ||
166 implKind == MethodHandleInfo.REF_invokeStatic && implClass.isHidden();
167 int parameterCount = factoryType.parameterCount();
168 ClassDesc[] argDescs;
169 MethodTypeDesc constructorTypeDesc;
300 // Assure no duplicate interfaces (ClassFormatError)
301 Set<ClassDesc> itfs = LinkedHashSet.newLinkedHashSet(altInterfaces.length + 1);
302 itfs.add(interfaceDesc);
303 for (Class<?> i : altInterfaces) {
304 itfs.add(classDesc(i));
305 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
306 }
307 interfaces = List.copyOf(itfs);
308 }
309 final boolean finalAccidentallySerializable = accidentallySerializable;
310 final byte[] classBytes = ClassFile.of().build(lambdaClassEntry, pool, new Consumer<ClassBuilder>() {
311 @Override
312 public void accept(ClassBuilder clb) {
313 clb.withFlags(ACC_SUPER | ACC_FINAL | ACC_SYNTHETIC)
314 .withInterfaceSymbols(interfaces);
315 // Generate final fields to be filled in by constructor
316 for (int i = 0; i < argDescs.length; i++) {
317 clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
318 }
319
320 generateConstructor(clb);
321
322 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
323 generateClassInitializer(clb);
324 }
325
326 // Forward the SAM method
327 clb.withMethodBody(interfaceMethodName,
328 methodDesc(interfaceMethodType),
329 ACC_PUBLIC,
330 forwardingMethod(interfaceMethodType));
331
332 // Forward the bridges
333 if (altMethods != null) {
334 for (MethodType mt : altMethods) {
335 clb.withMethodBody(interfaceMethodName,
336 methodDesc(mt),
337 ACC_PUBLIC | ACC_BRIDGE,
338 forwardingMethod(mt));
339 }
340 }
341
342 if (isSerializable)
343 generateSerializationFriendlyMethods(clb);
344 else if (finalAccidentallySerializable)
345 generateSerializationHostileMethods(clb);
346 }
347 });
348
349 // Define the generated class in this VM.
350
351 try {
352 // this class is linked at the indy callsite; so define a hidden nestmate
353 var classdata = useImplMethodHandle? implementation : null;
354 return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, NESTMATE_CLASS | STRONG_LOADER_LINK)
355 .defineClass(!disableEagerInitialization, classdata);
356
357 } catch (Throwable t) {
358 throw new InternalError(t);
359 }
360 }
361
362 /**
363 * Generate a static field and a static initializer that sets this field to an instance of the lambda
364 */
365 private void generateClassInitializer(ClassBuilder clb) {
366 ClassDesc lambdaTypeDescriptor = classDesc(factoryType.returnType());
367
368 // Generate the static final field that holds the lambda singleton
369 clb.withField(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
370
371 // Instantiate the lambda and store it to the static final field
372 clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, new Consumer<>() {
373 @Override
374 public void accept(CodeBuilder cob) {
375 assert factoryType.parameterCount() == 0;
376 cob.new_(lambdaClassEntry)
377 .dup()
378 .invokespecial(pool.methodRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(INIT_NAME, constructorTypeDesc)))
379 .putstatic(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor)))
380 .return_();
381 }
382 });
383 }
384
385 /**
386 * Generate the constructor for the class
387 */
388 private void generateConstructor(ClassBuilder clb) {
389 // Generate constructor
390 clb.withMethodBody(INIT_NAME, constructorTypeDesc, ACC_PRIVATE,
391 new Consumer<>() {
392 @Override
393 public void accept(CodeBuilder cob) {
394 cob.aload(0)
395 .invokespecial(CD_Object, INIT_NAME, MTD_void);
396 int parameterCount = factoryType.parameterCount();
397 for (int i = 0; i < parameterCount; i++) {
398 cob.aload(0)
399 .loadLocal(TypeKind.from(factoryType.parameterType(i)), cob.parameterSlot(i))
400 .putfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
443 .ldc(implInfo.getName())
444 .ldc(implInfo.getMethodType().toMethodDescriptorString())
445 .ldc(dynamicMethodType.toMethodDescriptorString())
446 .loadConstant(argDescs.length)
447 .anewarray(CD_Object);
448 for (int i = 0; i < argDescs.length; i++) {
449 cob.dup()
450 .loadConstant(i)
451 .aload(0)
452 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
453 TypeConvertingMethodAdapter.boxIfTypePrimitive(cob, TypeKind.from(argDescs[i]));
454 cob.aastore();
455 }
456 cob.invokespecial(SerializationSupport.CD_SerializedLambda, INIT_NAME,
457 SerializationSupport.MTD_CTOR_SERIALIZED_LAMBDA)
458 .areturn();
459 }
460 });
461 }
462
463 /**
464 * Generate a readObject/writeObject method that is hostile to serialization
465 */
466 private void generateSerializationHostileMethods(ClassBuilder clb) {
467 var hostileMethod = new Consumer<MethodBuilder>() {
468 @Override
469 public void accept(MethodBuilder mb) {
470 ConstantPoolBuilder cp = mb.constantPool();
471 ClassEntry nseCE = cp.classEntry(SerializationSupport.CD_NotSerializableException);
472 mb.with(ExceptionsAttribute.of(nseCE))
473 .withCode(new Consumer<CodeBuilder>() {
474 @Override
475 public void accept(CodeBuilder cob) {
476 cob.new_(nseCE)
477 .dup()
478 .ldc("Non-serializable lambda")
479 .invokespecial(cp.methodRefEntry(nseCE, cp.nameAndTypeEntry(INIT_NAME,
480 SerializationSupport.MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION)))
481 .athrow();
482 }
486 clb.withMethod(SerializationSupport.NAME_METHOD_WRITE_OBJECT, SerializationSupport.MTD_void_ObjectOutputStream,
487 ACC_PRIVATE + ACC_FINAL, hostileMethod);
488 clb.withMethod(SerializationSupport.NAME_METHOD_READ_OBJECT, SerializationSupport.MTD_void_ObjectInputStream,
489 ACC_PRIVATE + ACC_FINAL, hostileMethod);
490 }
491
492 /**
493 * This method generates a method body which calls the lambda implementation
494 * method, converting arguments, as needed.
495 */
496 Consumer<CodeBuilder> forwardingMethod(MethodType methodType) {
497 return new Consumer<>() {
498 @Override
499 public void accept(CodeBuilder cob) {
500 if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
501 cob.new_(implMethodClassDesc)
502 .dup();
503 }
504 if (useImplMethodHandle) {
505 ConstantPoolBuilder cp = cob.constantPool();
506 cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA), List.of()),
507 cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
508 }
509 for (int i = 0; i < argDescs.length; i++) {
510 cob.aload(0)
511 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
512 }
513
514 convertArgumentTypes(cob, methodType);
515
516 if (useImplMethodHandle) {
517 MethodType mtype = implInfo.getMethodType();
518 if (implKind != MethodHandleInfo.REF_invokeStatic) {
519 mtype = mtype.insertParameterTypes(0, implClass);
520 }
521 cob.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(mtype));
522 } else {
523 // Invoke the method we want to forward to
524 cob.invoke(invocationOpcode(), implMethodClassDesc, implMethodName, implMethodDesc, implClass.isInterface());
525 }
526 // Convert the return value (if any) and return it
|
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.invoke;
27
28 import jdk.internal.access.JavaLangInvokeAccess.ReflectableLambdaInfo;
29 import jdk.internal.constant.ClassOrInterfaceDescImpl;
30 import jdk.internal.misc.CDS;
31 import jdk.internal.util.ClassFileDumper;
32 import sun.invoke.util.VerifyAccess;
33
34 import java.io.Serializable;
35 import java.lang.classfile.ClassBuilder;
36 import java.lang.classfile.ClassFile;
37 import java.lang.classfile.CodeBuilder;
38 import java.lang.classfile.Label;
39 import java.lang.classfile.MethodBuilder;
40 import java.lang.classfile.Opcode;
41 import java.lang.classfile.TypeKind;
42 import java.lang.classfile.constantpool.MethodHandleEntry;
43 import java.lang.classfile.constantpool.NameAndTypeEntry;
44 import java.lang.constant.ClassDesc;
45 import java.lang.constant.MethodTypeDesc;
46 import java.lang.reflect.Modifier;
47 import java.util.LinkedHashSet;
48 import java.util.List;
49 import java.util.Set;
50 import java.util.function.Consumer;
51
52 import static java.lang.classfile.ClassFile.*;
53 import java.lang.classfile.attribute.ExceptionsAttribute;
54 import java.lang.classfile.constantpool.ClassEntry;
55 import java.lang.classfile.constantpool.ConstantPoolBuilder;
56
57 import static java.lang.constant.ConstantDescs.*;
58 import static java.lang.invoke.MethodHandleNatives.Constants.NESTMATE_CLASS;
59 import static java.lang.invoke.MethodHandleNatives.Constants.STRONG_LOADER_LINK;
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 // Static builders to avoid lambdas
77 record MethodBody(Consumer<CodeBuilder> code) implements Consumer<MethodBuilder> {
78 @Override
79 public void accept(MethodBuilder mb) {
80 mb.withCode(code);
81 }
82 };
83
84 // For dumping generated classes to disk, for debugging purposes
85 private static final ClassFileDumper lambdaProxyClassFileDumper;
86
87 private static final boolean disableEagerInitialization;
88
89 private static final String NAME_METHOD_QUOTED = "__internal_quoted";
90 private static final String QUOTED_FIELD_NAME = "quoted";
91 private static final String MODEL_FIELD_NAME = "model";
92
93 static {
94 // To dump the lambda proxy classes, set this system property:
95 // -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles
96 // or -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles=true
97 final String dumpProxyClassesKey = "jdk.invoke.LambdaMetafactory.dumpProxyClassFiles";
98 lambdaProxyClassFileDumper = ClassFileDumper.getInstance(dumpProxyClassesKey, "DUMP_LAMBDA_PROXY_CLASS_FILES");
99
100 final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
101 disableEagerInitialization = Boolean.getBoolean(disableEagerInitializationKey);
102 }
103
104 // See context values in AbstractValidatingLambdaMetafactory
105 private final ClassDesc implMethodClassDesc; // Name of type containing implementation "CC"
106 private final String implMethodName; // Name of implementation method "impl"
107 private final MethodTypeDesc implMethodDesc; // Type descriptor for implementation methods "(I)Ljava/lang/String;"
108 private final MethodType constructorType; // Generated class constructor type "(CC)void"
109 private final MethodTypeDesc constructorTypeDesc;// Type descriptor for the generated class constructor type "(CC)void"
110 private final ClassDesc[] argDescs; // Type descriptors for the constructor arguments
111 private final String lambdaClassName; // Generated name for the generated class "X$$Lambda$1"
112 private final ConstantPoolBuilder pool = ConstantPoolBuilder.of();
141 * substituted with their instantiation from
142 * the capture site
143 * @param isSerializable Should the lambda be made serializable? If set,
144 * either the target type or one of the additional SAM
145 * types must extend {@code Serializable}.
146 * @param altInterfaces Additional interfaces which the lambda object
147 * should implement.
148 * @param altMethods Method types for additional signatures to be
149 * implemented by invoking the implementation method
150 * @throws LambdaConversionException If any of the meta-factory protocol
151 * invariants are violated
152 */
153 public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
154 MethodType factoryType,
155 String interfaceMethodName,
156 MethodType interfaceMethodType,
157 MethodHandle implementation,
158 MethodType dynamicMethodType,
159 boolean isSerializable,
160 Class<?>[] altInterfaces,
161 MethodType[] altMethods,
162 ReflectableLambdaInfo reflectableLambdaInfo)
163 throws LambdaConversionException {
164 super(caller, factoryType, interfaceMethodName, interfaceMethodType,
165 implementation, dynamicMethodType,
166 isSerializable, altInterfaces, altMethods, reflectableLambdaInfo);
167 implMethodClassDesc = implClassDesc(implClass);
168 implMethodName = implInfo.getName();
169 implMethodDesc = methodDesc(implInfo.getMethodType());
170 constructorType = factoryType.changeReturnType(Void.TYPE);
171 lambdaClassName = lambdaClassName(targetClass);
172 lambdaClassEntry = pool.classEntry(ConstantUtils.internalNameToDesc(lambdaClassName));
173 // If the target class invokes a protected method inherited from a
174 // superclass in a different package, or does 'invokespecial', the
175 // lambda class has no access to the resolved method, or does
176 // 'invokestatic' on a hidden class which cannot be resolved by name.
177 // Instead, we need to pass the live implementation method handle to
178 // the proxy class to invoke directly. (javac prefers to avoid this
179 // situation by generating bridges in the target class)
180 useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
181 !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
182 implKind == MethodHandleInfo.REF_invokeSpecial ||
183 implKind == MethodHandleInfo.REF_invokeStatic && implClass.isHidden();
184 int parameterCount = factoryType.parameterCount();
185 ClassDesc[] argDescs;
186 MethodTypeDesc constructorTypeDesc;
317 // Assure no duplicate interfaces (ClassFormatError)
318 Set<ClassDesc> itfs = LinkedHashSet.newLinkedHashSet(altInterfaces.length + 1);
319 itfs.add(interfaceDesc);
320 for (Class<?> i : altInterfaces) {
321 itfs.add(classDesc(i));
322 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
323 }
324 interfaces = List.copyOf(itfs);
325 }
326 final boolean finalAccidentallySerializable = accidentallySerializable;
327 final byte[] classBytes = ClassFile.of().build(lambdaClassEntry, pool, new Consumer<ClassBuilder>() {
328 @Override
329 public void accept(ClassBuilder clb) {
330 clb.withFlags(ACC_SUPER | ACC_FINAL | ACC_SYNTHETIC)
331 .withInterfaceSymbols(interfaces);
332 // Generate final fields to be filled in by constructor
333 for (int i = 0; i < argDescs.length; i++) {
334 clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
335 }
336
337 if (reflectableLambdaInfo != null) {
338 // the field that will hold the quoted instance
339 clb.withField(QUOTED_FIELD_NAME, reflectableLambdaInfo.quotedClass(), ACC_PRIVATE);
340 // the field that will hold the model
341 clb.withField(MODEL_FIELD_NAME, reflectableLambdaInfo.funcOpClass(),
342 ACC_PRIVATE | ACC_STATIC);
343 }
344
345 generateConstructor(clb);
346
347 generateClassInitializationMethod(clb);
348
349
350 // Forward the SAM method
351 clb.withMethodBody(interfaceMethodName,
352 methodDesc(interfaceMethodType),
353 ACC_PUBLIC,
354 forwardingMethod(interfaceMethodType));
355
356 // Forward the bridges
357 if (altMethods != null) {
358 for (MethodType mt : altMethods) {
359 clb.withMethodBody(interfaceMethodName,
360 methodDesc(mt),
361 ACC_PUBLIC | ACC_BRIDGE,
362 forwardingMethod(mt));
363 }
364 }
365
366 if (isSerializable)
367 generateSerializationFriendlyMethods(clb);
368 else if (finalAccidentallySerializable)
369 generateSerializationHostileMethods(clb);
370
371 if (reflectableLambdaInfo != null) {
372 generateQuotedMethod(clb);
373 }
374 }
375 });
376
377 // Define the generated class in this VM.
378
379 try {
380 // this class is linked at the indy callsite; so define a hidden nestmate
381 List<?> classdata;
382 if (useImplMethodHandle || reflectableLambdaInfo != null) {
383 classdata = reflectableLambdaInfo == null ?
384 List.of(implementation) :
385 List.of(implementation, reflectableLambdaInfo.opHandle(), reflectableLambdaInfo.extractOpHandle());
386 } else {
387 classdata = null;
388 }
389 return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, NESTMATE_CLASS | STRONG_LOADER_LINK)
390 .defineClass(!disableEagerInitialization, classdata);
391
392 } catch (Throwable t) {
393 throw new InternalError(t);
394 }
395 }
396
397 private void generateClassInitializationMethod(ClassBuilder clb) {
398 if (!(factoryType.parameterCount() == 0 && disableEagerInitialization) && reflectableLambdaInfo == null) {
399 return;
400 }
401 clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, new Consumer<CodeBuilder>() {
402 @Override
403 public void accept(CodeBuilder cob) {
404 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
405 ClassDesc lambdaTypeDescriptor = classDesc(factoryType.returnType());
406 // Generate the static final field that holds the lambda singleton
407 clb.withField(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
408 cob.new_(lambdaClassEntry)
409 .dup()
410 .invokespecial(pool.methodRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(INIT_NAME, constructorTypeDesc)))
411 .putstatic(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor)));
412 }
413 cob.return_();
414 }
415 });
416 }
417
418 /**
419 * Generate the constructor for the class
420 */
421 private void generateConstructor(ClassBuilder clb) {
422 // Generate constructor
423 clb.withMethodBody(INIT_NAME, constructorTypeDesc, ACC_PRIVATE,
424 new Consumer<>() {
425 @Override
426 public void accept(CodeBuilder cob) {
427 cob.aload(0)
428 .invokespecial(CD_Object, INIT_NAME, MTD_void);
429 int parameterCount = factoryType.parameterCount();
430 for (int i = 0; i < parameterCount; i++) {
431 cob.aload(0)
432 .loadLocal(TypeKind.from(factoryType.parameterType(i)), cob.parameterSlot(i))
433 .putfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
476 .ldc(implInfo.getName())
477 .ldc(implInfo.getMethodType().toMethodDescriptorString())
478 .ldc(dynamicMethodType.toMethodDescriptorString())
479 .loadConstant(argDescs.length)
480 .anewarray(CD_Object);
481 for (int i = 0; i < argDescs.length; i++) {
482 cob.dup()
483 .loadConstant(i)
484 .aload(0)
485 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
486 TypeConvertingMethodAdapter.boxIfTypePrimitive(cob, TypeKind.from(argDescs[i]));
487 cob.aastore();
488 }
489 cob.invokespecial(SerializationSupport.CD_SerializedLambda, INIT_NAME,
490 SerializationSupport.MTD_CTOR_SERIALIZED_LAMBDA)
491 .areturn();
492 }
493 });
494 }
495
496 /**
497 * Generate method #__internal_quoted()
498 */
499 private void generateQuotedMethod(ClassBuilder clb) {
500 clb.withMethod(NAME_METHOD_QUOTED, MethodTypeDesc.of(reflectableLambdaInfo.quotedClass()), ACC_PRIVATE, new MethodBody(new Consumer<CodeBuilder>() {
501 @Override
502 public void accept(CodeBuilder cob) {
503 cob.aload(0)
504 .invokevirtual(lambdaClassEntry.asSymbol(), "getQuoted", MethodTypeDesc.of(reflectableLambdaInfo.quotedClass()))
505 .areturn();
506 }
507 }));
508 // generate helper methods
509 /*
510 synchronized Quoted getQuoted() {
511 Quoted v = quoted;
512 if (v == null) {
513 v = quoted = Quoted.extractOp(getModel(), captures);
514 }
515 return v;
516 }
517 * */
518 clb.withMethod("getQuoted", MethodTypeDesc.of(reflectableLambdaInfo.quotedClass()),
519 ACC_PRIVATE + ACC_SYNCHRONIZED,
520 new MethodBody(new Consumer<CodeBuilder>() {
521 @Override
522 public void accept(CodeBuilder cob) {
523 cob.aload(0)
524 .getfield(lambdaClassEntry.asSymbol(), QUOTED_FIELD_NAME, reflectableLambdaInfo.quotedClass())
525 .astore(1)
526 .aload(1)
527 .ifThen(Opcode.IFNULL, bcb -> {
528 bcb.aload(0); // will be used by putfield
529
530 // load class data: MH to Quoted.extractOp
531 ConstantPoolBuilder cp = bcb.constantPool();
532 MethodHandleEntry bsmDataAt = cp.methodHandleEntry(BSM_CLASS_DATA_AT);
533 NameAndTypeEntry natMH = cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle);
534 bcb.ldc(cp.constantDynamicEntry(cp.bsmEntry(bsmDataAt, List.of(cp.intEntry(2))), natMH));
535
536 bcb.invokestatic(lambdaClassEntry.asSymbol(), "getModel", MethodTypeDesc.of(reflectableLambdaInfo.funcOpClass()));
537
538 // load captured args in array
539 int capturedArity = factoryType.parameterCount();
540 bcb.loadConstant(capturedArity)
541 .anewarray(CD_Object);
542 for (int i = 0; i < capturedArity; i++) {
543 bcb.dup()
544 .loadConstant(i)
545 .aload(0)
546 .getfield(lambdaClassEntry.asSymbol(), argName(i), argDescs[i]);
547 TypeConvertingMethodAdapter.boxIfTypePrimitive(bcb, TypeKind.from(argDescs[i]));
548 bcb.aastore();
549 }
550
551 // invoke Quoted.extractOp
552 bcb.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(reflectableLambdaInfo.extractOpHandle().type()))
553 .dup_x1()
554 .putfield(lambdaClassEntry.asSymbol(), QUOTED_FIELD_NAME, reflectableLambdaInfo.quotedClass())
555 .astore(1);
556
557 })
558 .aload(1)
559 .areturn();
560 }
561 }));
562
563 /*
564 private static synchronized CoreOp.FuncOp getModel() {
565 FuncOp v = model;
566 if (v == null) {
567 v = model = ...invoke lambda op building method...
568 }
569 return v;
570 }
571 * */
572 clb.withMethod("getModel", MethodTypeDesc.of(reflectableLambdaInfo.funcOpClass()),
573 ACC_PRIVATE + ACC_STATIC + ACC_SYNCHRONIZED,
574 new MethodBody(new Consumer<CodeBuilder>() {
575 @Override
576 public void accept(CodeBuilder cob) {
577 ClassDesc funcOpClassDesc = reflectableLambdaInfo.funcOpClass();
578 cob.getstatic(lambdaClassEntry.asSymbol(), MODEL_FIELD_NAME, funcOpClassDesc)
579 .astore(0)
580 .aload(0)
581 .ifThen(Opcode.IFNULL, bcb -> {
582 // load class data: MH to op building method
583 ConstantPoolBuilder cp = pool;
584 MethodHandleEntry bsmDataAt = cp.methodHandleEntry(BSM_CLASS_DATA_AT);
585 NameAndTypeEntry natMH = cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle);
586 cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(bsmDataAt, List.of(cp.intEntry(1))), natMH));
587 MethodType mtype = quotableOpGetterInfo.getMethodType();
588 cob.invokevirtual(CD_MethodHandle, "invokeExact", mtype.describeConstable().get())
589 .checkcast(funcOpClassDesc)
590 .dup()
591 .putstatic(lambdaClassEntry.asSymbol(), MODEL_FIELD_NAME, funcOpClassDesc)
592 .astore(0);
593 })
594 .aload(0)
595 .areturn();
596 }
597 }));
598 }
599
600 /**
601 * Generate a readObject/writeObject method that is hostile to serialization
602 */
603 private void generateSerializationHostileMethods(ClassBuilder clb) {
604 var hostileMethod = new Consumer<MethodBuilder>() {
605 @Override
606 public void accept(MethodBuilder mb) {
607 ConstantPoolBuilder cp = mb.constantPool();
608 ClassEntry nseCE = cp.classEntry(SerializationSupport.CD_NotSerializableException);
609 mb.with(ExceptionsAttribute.of(nseCE))
610 .withCode(new Consumer<CodeBuilder>() {
611 @Override
612 public void accept(CodeBuilder cob) {
613 cob.new_(nseCE)
614 .dup()
615 .ldc("Non-serializable lambda")
616 .invokespecial(cp.methodRefEntry(nseCE, cp.nameAndTypeEntry(INIT_NAME,
617 SerializationSupport.MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION)))
618 .athrow();
619 }
623 clb.withMethod(SerializationSupport.NAME_METHOD_WRITE_OBJECT, SerializationSupport.MTD_void_ObjectOutputStream,
624 ACC_PRIVATE + ACC_FINAL, hostileMethod);
625 clb.withMethod(SerializationSupport.NAME_METHOD_READ_OBJECT, SerializationSupport.MTD_void_ObjectInputStream,
626 ACC_PRIVATE + ACC_FINAL, hostileMethod);
627 }
628
629 /**
630 * This method generates a method body which calls the lambda implementation
631 * method, converting arguments, as needed.
632 */
633 Consumer<CodeBuilder> forwardingMethod(MethodType methodType) {
634 return new Consumer<>() {
635 @Override
636 public void accept(CodeBuilder cob) {
637 if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
638 cob.new_(implMethodClassDesc)
639 .dup();
640 }
641 if (useImplMethodHandle) {
642 ConstantPoolBuilder cp = cob.constantPool();
643 cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA_AT), List.of(cp.intEntry(0))),
644 cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
645 }
646 for (int i = 0; i < argDescs.length; i++) {
647 cob.aload(0)
648 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
649 }
650
651 convertArgumentTypes(cob, methodType);
652
653 if (useImplMethodHandle) {
654 MethodType mtype = implInfo.getMethodType();
655 if (implKind != MethodHandleInfo.REF_invokeStatic) {
656 mtype = mtype.insertParameterTypes(0, implClass);
657 }
658 cob.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(mtype));
659 } else {
660 // Invoke the method we want to forward to
661 cob.invoke(invocationOpcode(), implMethodClassDesc, implMethodName, implMethodDesc, implClass.isInterface());
662 }
663 // Convert the return value (if any) and return it
|