1 /*
2 * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang.invoke;
27
28 import jdk.internal.access.JavaLangAccess;
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;
80
81 private static final boolean disableEagerInitialization;
82
83 static {
84 // To dump the lambda proxy classes, set this system property:
85 // -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles
86 // or -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles=true
87 final String dumpProxyClassesKey = "jdk.invoke.LambdaMetafactory.dumpProxyClassFiles";
88 lambdaProxyClassFileDumper = ClassFileDumper.getInstance(dumpProxyClassesKey, "DUMP_LAMBDA_PROXY_CLASS_FILES");
89
90 final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
91 disableEagerInitialization = Boolean.getBoolean(disableEagerInitializationKey);
92 }
93
94 // See context values in AbstractValidatingLambdaMetafactory
95 private final ClassDesc implMethodClassDesc; // Name of type containing implementation "CC"
96 private final String implMethodName; // Name of implementation method "impl"
97 private final MethodTypeDesc implMethodDesc; // Type descriptor for implementation methods "(I)Ljava/lang/String;"
98 private final MethodType constructorType; // Generated class constructor type "(CC)void"
99 private final MethodTypeDesc constructorTypeDesc;// Type descriptor for the generated class constructor type "(CC)void"
100 private final ClassDesc[] argDescs; // Type descriptors for the constructor arguments
101 private final String lambdaClassName; // Generated name for the generated class "X$$Lambda$1"
102 private final ConstantPoolBuilder pool = ConstantPoolBuilder.of();
103 private final ClassEntry lambdaClassEntry; // Class entry for the generated class "X$$Lambda$1"
104 private final boolean useImplMethodHandle; // use MethodHandle invocation instead of symbolic bytecode invocation
105
106 /**
107 * General meta-factory constructor, supporting both standard cases and
108 * allowing for uncommon options such as serialization or bridging.
109 *
110 * @param caller Stacked automatically by VM; represents a lookup context
111 * with the accessibility privileges of the caller.
112 * @param factoryType Stacked automatically by VM; the signature of the
113 * invoked method, which includes the expected static
114 * type of the returned lambda object, and the static
115 * types of the captured arguments for the lambda. In
116 * the event that the implementation method is an
117 * instance method, the first argument in the invocation
118 * signature will correspond to the receiver.
119 * @param interfaceMethodName Name of the method in the functional interface to
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;
180 if (parameterCount > 0) {
181 argDescs = new ClassDesc[parameterCount];
182 for (int i = 0; i < parameterCount; i++) {
183 argDescs[i] = classDesc(factoryType.parameterType(i));
184 }
185 constructorTypeDesc = MethodTypeDescImpl.ofValidated(CD_void, argDescs);
186 } else {
187 argDescs = EMPTY_CLASSDESC_ARRAY;
188 constructorTypeDesc = MTD_void;
189 }
190 this.argDescs = argDescs;
191 this.constructorTypeDesc = constructorTypeDesc;
192 }
193
194 private static String argName(int i) {
195 return i < ARG_NAME_CACHE.length ? ARG_NAME_CACHE[i] : "arg$" + (i + 1);
196 }
197
198 private static String sanitizedTargetClassName(Class<?> targetClass) {
199 String name = targetClass.getName();
200 if (targetClass.isHidden()) {
201 // use the original class name
202 name = name.replace('/', '_');
203 }
204 return name.replace('.', '/');
205 }
206
207 private static String lambdaClassName(Class<?> targetClass) {
208 return sanitizedTargetClassName(targetClass).concat("$$Lambda");
209 }
210
211 /**
212 * Build the CallSite. Generate a class file which implements the functional
213 * interface, define the class, if there are no parameters create an instance
214 * of the class which the CallSite will return, otherwise, generate handles
215 * which will call the class' constructor.
216 *
217 * @return a CallSite, which, when invoked, will return an instance of the
218 * functional interface
219 * @throws LambdaConversionException If properly formed functional interface
220 * is not found
221 */
222 @Override
223 CallSite buildCallSite() throws LambdaConversionException {
224 final Class<?> innerClass = spinInnerClass();
225 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
226 try {
227 return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
228 factoryType.returnType()));
229 } catch (ReflectiveOperationException e) {
230 throw new LambdaConversionException(
231 "Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e);
232 }
233 } else {
234 try {
235 MethodHandle mh = caller.findConstructor(innerClass, constructorType);
236 if (factoryType.parameterCount() == 0) {
237 // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance
238 Object inst = mh.invokeBasic();
239 return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
240 } else {
241 return new ConstantCallSite(mh.asType(factoryType));
242 }
243 } catch (ReflectiveOperationException e) {
244 throw new LambdaConversionException("Exception finding constructor", e);
245 } catch (Throwable e) {
246 throw new LambdaConversionException("Exception instantiating lambda object", e);
247 }
248 }
249 }
250
251 /**
252 * Spins the lambda proxy class.
253 *
254 * This first checks if a lambda proxy class can be loaded from CDS archive.
255 * Otherwise, generate the lambda proxy class. If CDS dumping is enabled, it
256 * registers the lambda proxy class for including into the CDS archive.
257 */
258 private Class<?> spinInnerClass() throws LambdaConversionException {
259 // CDS does not handle disableEagerInitialization or useImplMethodHandle
260 if (!disableEagerInitialization && !useImplMethodHandle) {
261 if (CDS.isUsingArchive()) {
262 // load from CDS archive if present
263 Class<?> innerClass = LambdaProxyClassArchive.find(targetClass,
264 interfaceMethodName,
265 factoryType,
266 interfaceMethodType,
267 implementation,
268 dynamicMethodType,
269 isSerializable,
270 altInterfaces,
271 altMethods);
272 if (innerClass != null) return innerClass;
273 }
274
275 // include lambda proxy class in CDS archive at dump time
276 if (CDS.isDumpingArchive()) {
277 Class<?> innerClass = generateInnerClass();
278 LambdaProxyClassArchive.register(targetClass,
279 interfaceMethodName,
280 factoryType,
281 interfaceMethodType,
282 implementation,
283 dynamicMethodType,
284 isSerializable,
285 altInterfaces,
286 altMethods,
287 innerClass);
288 return innerClass;
289 }
290
291 }
292 return generateInnerClass();
293 }
294
295 /**
296 * Generate a class file which implements the functional
297 * interface, define and return the class.
298 *
299 * @return a Class which implements the functional interface
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;
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 .return_();
409 }
410 });
411 }
412
413 /**
414 * Generate the constructor for the class
415 */
416 private void generateConstructor(ClassBuilder clb) {
417 // Generate constructor
418 clb.withMethodBody(INIT_NAME, constructorTypeDesc, ACC_PRIVATE,
419 new Consumer<>() {
420 @Override
421 public void accept(CodeBuilder cob) {
422 int parameterCount = factoryType.parameterCount();
423 for (int i = 0; i < parameterCount; i++) {
424 cob.aload(0)
425 .loadLocal(TypeKind.from(factoryType.parameterType(i)), cob.parameterSlot(i))
426 .putfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
427 }
428 cob.aload(0)
429 .invokespecial(CD_Object, INIT_NAME, MTD_void)
430 .return_();
431 }
432 });
433 }
434
435 private static class SerializationSupport {
436 // Serialization support
437 private static final ClassDesc CD_SerializedLambda = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/invoke/SerializedLambda;");
438 private static final ClassDesc CD_ObjectOutputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectOutputStream;");
439 private static final ClassDesc CD_ObjectInputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectInputStream;");
440 private static final MethodTypeDesc MTD_Object = MethodTypeDescImpl.ofValidated(CD_Object);
441 private static final MethodTypeDesc MTD_void_ObjectOutputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectOutputStream);
442 private static final MethodTypeDesc MTD_void_ObjectInputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectInputStream);
443
444 private static final String NAME_METHOD_WRITE_REPLACE = "writeReplace";
445 private static final String NAME_METHOD_READ_OBJECT = "readObject";
446 private static final String NAME_METHOD_WRITE_OBJECT = "writeObject";
447
448 static final ClassDesc CD_NotSerializableException = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/NotSerializableException;");
449 static final MethodTypeDesc MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION = MethodTypeDescImpl.ofValidated(CD_void, CD_String);
450 static final MethodTypeDesc MTD_CTOR_SERIALIZED_LAMBDA = MethodTypeDescImpl.ofValidated(CD_void,
451 CD_Class, CD_String, CD_String, CD_String, CD_int, CD_String, CD_String, CD_String, CD_String, ConstantUtils.CD_Object_array);
452
453 }
454
455 /**
456 * Generate a writeReplace method that supports serialization
457 */
458 private void generateSerializationFriendlyMethods(ClassBuilder clb) {
459 clb.withMethodBody(SerializationSupport.NAME_METHOD_WRITE_REPLACE, SerializationSupport.MTD_Object, ACC_PRIVATE | ACC_FINAL,
460 new Consumer<>() {
461 @Override
462 public void accept(CodeBuilder cob) {
463 cob.new_(SerializationSupport.CD_SerializedLambda)
464 .dup()
465 .ldc(ClassDesc.ofInternalName(sanitizedTargetClassName(targetClass)))
466 .ldc(factoryType.returnType().getName().replace('.', '/'))
467 .ldc(interfaceMethodName)
468 .ldc(interfaceMethodType.toMethodDescriptorString())
469 .ldc(implInfo.getReferenceKind())
470 .ldc(implInfo.getDeclaringClass().getName().replace('.', '/'))
471 .ldc(implInfo.getName())
472 .ldc(implInfo.getMethodType().toMethodDescriptorString())
473 .ldc(dynamicMethodType.toMethodDescriptorString())
474 .loadConstant(argDescs.length)
475 .anewarray(CD_Object);
476 for (int i = 0; i < argDescs.length; i++) {
477 cob.dup()
478 .loadConstant(i)
479 .aload(0)
480 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
481 TypeConvertingMethodAdapter.boxIfTypePrimitive(cob, TypeKind.from(argDescs[i]));
482 cob.aastore();
483 }
484 cob.invokespecial(SerializationSupport.CD_SerializedLambda, INIT_NAME,
485 SerializationSupport.MTD_CTOR_SERIALIZED_LAMBDA)
486 .areturn();
487 }
488 });
489 }
490
491 /**
492 * Generate a readObject/writeObject method that is hostile to serialization
493 */
494 private void generateSerializationHostileMethods(ClassBuilder clb) {
495 var hostileMethod = new Consumer<MethodBuilder>() {
496 @Override
497 public void accept(MethodBuilder mb) {
498 ConstantPoolBuilder cp = mb.constantPool();
499 ClassEntry nseCE = cp.classEntry(SerializationSupport.CD_NotSerializableException);
500 mb.with(ExceptionsAttribute.of(nseCE))
501 .withCode(new Consumer<CodeBuilder>() {
502 @Override
503 public void accept(CodeBuilder cob) {
504 cob.new_(nseCE)
505 .dup()
506 .ldc("Non-serializable lambda")
507 .invokespecial(cp.methodRefEntry(nseCE, cp.nameAndTypeEntry(INIT_NAME,
508 SerializationSupport.MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION)))
509 .athrow();
510 }
511 });
512 }
513 };
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
555 // Note: if adapting from non-void to void, the 'return'
556 // instruction will pop the unneeded result
557 Class<?> implReturnClass = implMethodType.returnType();
558 Class<?> samReturnClass = methodType.returnType();
559 TypeConvertingMethodAdapter.convertType(cob, implReturnClass, samReturnClass, samReturnClass);
560 cob.return_(TypeKind.from(samReturnClass));
561 }
562 };
563 }
564
565 private void convertArgumentTypes(CodeBuilder cob, MethodType samType) {
566 int samParametersLength = samType.parameterCount();
567 int captureArity = factoryType.parameterCount();
568 for (int i = 0; i < samParametersLength; i++) {
569 Class<?> argType = samType.parameterType(i);
570 cob.loadLocal(TypeKind.from(argType), cob.parameterSlot(i));
571 TypeConvertingMethodAdapter.convertType(cob, argType, implMethodType.parameterType(captureArity + i), dynamicMethodType.parameterType(i));
572 }
573 }
574
575 private Opcode invocationOpcode() throws InternalError {
576 return switch (implKind) {
577 case MethodHandleInfo.REF_invokeStatic -> Opcode.INVOKESTATIC;
578 case MethodHandleInfo.REF_newInvokeSpecial -> Opcode.INVOKESPECIAL;
579 case MethodHandleInfo.REF_invokeVirtual -> Opcode.INVOKEVIRTUAL;
580 case MethodHandleInfo.REF_invokeInterface -> Opcode.INVOKEINTERFACE;
581 case MethodHandleInfo.REF_invokeSpecial -> Opcode.INVOKESPECIAL;
582 default -> throw new InternalError("Unexpected invocation kind: " + implKind);
583 };
584 }
585
586 static ClassDesc implClassDesc(Class<?> cls) {
587 return cls.isHidden() ? null : ConstantUtils.referenceClassDesc(cls.descriptorString());
588 }
589
590 static ClassDesc classDesc(Class<?> cls) {
591 return cls.isPrimitive() ? Wrapper.forPrimitiveType(cls).basicClassDescriptor()
592 : ConstantUtils.referenceClassDesc(cls.descriptorString());
593 }
594
595 static MethodTypeDesc methodDesc(MethodType mt) {
596 var params = new ClassDesc[mt.parameterCount()];
597 for (int i = 0; i < params.length; i++) {
598 params[i] = classDesc(mt.parameterType(i));
599 }
600 return MethodTypeDescImpl.ofValidated(classDesc(mt.returnType()), params);
601 }
602 }