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