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.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();
97 private final ClassEntry lambdaClassEntry; // Class entry for the generated class "X$$Lambda$1"
98 private final boolean useImplMethodHandle; // use MethodHandle invocation instead of symbolic bytecode invocation
99
100 /**
101 * General meta-factory constructor, supporting both standard cases and
102 * allowing for uncommon options such as serialization or bridging.
103 *
104 * @param caller Stacked automatically by VM; represents a lookup context
105 * with the accessibility privileges of the caller.
106 * @param factoryType Stacked automatically by VM; the signature of the
107 * invoked method, which includes the expected static
108 * type of the returned lambda object, and the static
109 * types of the captured arguments for the lambda. In
110 * the event that the implementation method is an
111 * instance method, the first argument in the invocation
112 * signature will correspond to the receiver.
113 * @param interfaceMethodName Name of the method in the functional interface to
114 * which the lambda or method reference is being
115 * converted, represented as a String.
116 * @param interfaceMethodType Type of the method in the functional interface to
117 * which the lambda or method reference is being
118 * converted, represented as a MethodType.
119 * @param implementation The implementation method which should be called (with
120 * suitable adaptation of argument types, return types,
121 * and adjustment for captured arguments) when methods of
122 * the resulting functional interface instance are invoked.
123 * @param dynamicMethodType The signature of the primary functional
124 * interface method after type variables are
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;
170 if (parameterCount > 0) {
171 argDescs = new ClassDesc[parameterCount];
172 for (int i = 0; i < parameterCount; i++) {
173 argDescs[i] = classDesc(factoryType.parameterType(i));
174 }
175 constructorTypeDesc = MethodTypeDescImpl.ofValidated(CD_void, argDescs);
176 } else {
177 argDescs = EMPTY_CLASSDESC_ARRAY;
178 constructorTypeDesc = MTD_void;
179 }
180 this.argDescs = argDescs;
181 this.constructorTypeDesc = constructorTypeDesc;
182 }
183
184 private static String argName(int i) {
185 return i < ARG_NAME_CACHE.length ? ARG_NAME_CACHE[i] : "arg$" + (i + 1);
186 }
187
188 private static String sanitizedTargetClassName(Class<?> targetClass) {
189 String name = targetClass.getName();
190 if (targetClass.isHidden()) {
191 // use the original class name
192 name = name.replace('/', '_');
193 }
194 return name.replace('.', '/');
195 }
196
197 private static String lambdaClassName(Class<?> targetClass) {
198 return sanitizedTargetClassName(targetClass).concat("$$Lambda");
199 }
200
201 /**
202 * Build the CallSite. Generate a class file which implements the functional
203 * interface, define the class, if there are no parameters create an instance
204 * of the class which the CallSite will return, otherwise, generate handles
205 * which will call the class' constructor.
206 *
207 * @return a CallSite, which, when invoked, will return an instance of the
208 * functional interface
209 * @throws LambdaConversionException If properly formed functional interface
210 * is not found
211 */
212 @Override
213 CallSite buildCallSite() throws LambdaConversionException {
214 final Class<?> innerClass = spinInnerClass();
215 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
216 try {
217 return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
218 factoryType.returnType()));
219 } catch (ReflectiveOperationException e) {
220 throw new LambdaConversionException(
221 "Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e);
222 }
223 } else {
224 try {
225 MethodHandle mh = caller.findConstructor(innerClass, constructorType);
226 if (factoryType.parameterCount() == 0) {
227 // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance
228 Object inst = mh.invokeBasic();
229 return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
230 } else {
231 return new ConstantCallSite(mh.asType(factoryType));
232 }
233 } catch (ReflectiveOperationException e) {
234 throw new LambdaConversionException("Exception finding constructor", e);
235 } catch (Throwable e) {
236 throw new LambdaConversionException("Exception instantiating lambda object", e);
237 }
238 }
239 }
240
241 /**
242 * Spins the lambda proxy class.
243 *
244 * This first checks if a lambda proxy class can be loaded from CDS archive.
245 * Otherwise, generate the lambda proxy class. If CDS dumping is enabled, it
246 * registers the lambda proxy class for including into the CDS archive.
247 */
248 private Class<?> spinInnerClass() throws LambdaConversionException {
249 // CDS does not handle disableEagerInitialization or useImplMethodHandle
250 if (!disableEagerInitialization && !useImplMethodHandle) {
251 if (CDS.isUsingArchive()) {
252 // load from CDS archive if present
253 Class<?> innerClass = LambdaProxyClassArchive.find(targetClass,
254 interfaceMethodName,
255 factoryType,
256 interfaceMethodType,
257 implementation,
258 dynamicMethodType,
259 isSerializable,
260 altInterfaces,
261 altMethods);
262 if (innerClass != null) return innerClass;
263 }
264
265 // include lambda proxy class in CDS archive at dump time
266 if (CDS.isDumpingArchive()) {
267 Class<?> innerClass = generateInnerClass();
268 LambdaProxyClassArchive.register(targetClass,
269 interfaceMethodName,
270 factoryType,
271 interfaceMethodType,
272 implementation,
273 dynamicMethodType,
274 isSerializable,
275 altInterfaces,
276 altMethods,
277 innerClass);
278 return innerClass;
279 }
280
281 }
282 return generateInnerClass();
283 }
284
285 /**
286 * Generate a class file which implements the functional
287 * interface, define and return the class.
288 *
289 * @return a Class which implements the functional interface
290 * @throws LambdaConversionException If properly formed functional interface
291 * is not found
292 */
293 private Class<?> generateInnerClass() throws LambdaConversionException {
294 List<ClassDesc> interfaces;
295 ClassDesc interfaceDesc = classDesc(interfaceClass);
296 boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
297 if (altInterfaces.length == 0) {
298 interfaces = List.of(interfaceDesc);
299 } else {
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 // All Classes in the BSM argument method types are loaded; no need for LoadableDescriptors
316
317 // Generate final fields to be filled in by constructor
318 for (int i = 0; i < argDescs.length; i++) {
319 clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
320 }
321
322 generateConstructor(clb);
323
324 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
325 generateClassInitializer(clb);
326 }
327
328 // Forward the SAM method
329 clb.withMethodBody(interfaceMethodName,
330 methodDesc(interfaceMethodType),
331 ACC_PUBLIC,
332 forwardingMethod(interfaceMethodType));
333
334 // Forward the bridges
335 if (altMethods != null) {
336 for (MethodType mt : altMethods) {
337 clb.withMethodBody(interfaceMethodName,
338 methodDesc(mt),
339 ACC_PUBLIC | ACC_BRIDGE,
340 forwardingMethod(mt));
341 }
342 }
343
344 if (isSerializable)
345 generateSerializationFriendlyMethods(clb);
346 else if (finalAccidentallySerializable)
347 generateSerializationHostileMethods(clb);
348 }
349 });
350
351 // Define the generated class in this VM.
352
353 try {
354 // this class is linked at the indy callsite; so define a hidden nestmate
355 var classdata = useImplMethodHandle? implementation : null;
356 return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, NESTMATE_CLASS | STRONG_LOADER_LINK)
357 .defineClass(!disableEagerInitialization, classdata);
358
359 } catch (Throwable t) {
360 throw new InternalError(t);
361 }
362 }
363
364 /**
365 * Generate a static field and a static initializer that sets this field to an instance of the lambda
366 */
367 private void generateClassInitializer(ClassBuilder clb) {
368 ClassDesc lambdaTypeDescriptor = classDesc(factoryType.returnType());
369
370 // Generate the static final field that holds the lambda singleton
371 clb.withField(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
372
373 // Instantiate the lambda and store it to the static final field
374 clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, new Consumer<>() {
375 @Override
376 public void accept(CodeBuilder cob) {
377 assert factoryType.parameterCount() == 0;
378 cob.new_(lambdaClassEntry)
379 .dup()
380 .invokespecial(pool.methodRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(INIT_NAME, constructorTypeDesc)))
381 .putstatic(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor)))
382 .return_();
383 }
384 });
385 }
386
387 /**
388 * Generate the constructor for the class
389 */
390 private void generateConstructor(ClassBuilder clb) {
391 // Generate constructor
392 clb.withMethodBody(INIT_NAME, constructorTypeDesc, ACC_PRIVATE,
393 new Consumer<>() {
394 @Override
395 public void accept(CodeBuilder cob) {
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.aload(0)
403 .invokespecial(CD_Object, INIT_NAME, MTD_void)
404 .return_();
405 }
406 });
407 }
408
409 private static class SerializationSupport {
410 // Serialization support
411 private static final ClassDesc CD_SerializedLambda = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/invoke/SerializedLambda;");
412 private static final ClassDesc CD_ObjectOutputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectOutputStream;");
413 private static final ClassDesc CD_ObjectInputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectInputStream;");
414 private static final MethodTypeDesc MTD_Object = MethodTypeDescImpl.ofValidated(CD_Object);
415 private static final MethodTypeDesc MTD_void_ObjectOutputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectOutputStream);
416 private static final MethodTypeDesc MTD_void_ObjectInputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectInputStream);
417
418 private static final String NAME_METHOD_WRITE_REPLACE = "writeReplace";
419 private static final String NAME_METHOD_READ_OBJECT = "readObject";
420 private static final String NAME_METHOD_WRITE_OBJECT = "writeObject";
421
422 static final ClassDesc CD_NotSerializableException = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/NotSerializableException;");
423 static final MethodTypeDesc MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION = MethodTypeDescImpl.ofValidated(CD_void, CD_String);
424 static final MethodTypeDesc MTD_CTOR_SERIALIZED_LAMBDA = MethodTypeDescImpl.ofValidated(CD_void,
425 CD_Class, CD_String, CD_String, CD_String, CD_int, CD_String, CD_String, CD_String, CD_String, ConstantUtils.CD_Object_array);
426
427 }
428
429 /**
430 * Generate a writeReplace method that supports serialization
431 */
432 private void generateSerializationFriendlyMethods(ClassBuilder clb) {
433 clb.withMethodBody(SerializationSupport.NAME_METHOD_WRITE_REPLACE, SerializationSupport.MTD_Object, ACC_PRIVATE | ACC_FINAL,
434 new Consumer<>() {
435 @Override
436 public void accept(CodeBuilder cob) {
437 cob.new_(SerializationSupport.CD_SerializedLambda)
438 .dup()
439 .ldc(ClassDesc.ofInternalName(sanitizedTargetClassName(targetClass)))
440 .ldc(factoryType.returnType().getName().replace('.', '/'))
441 .ldc(interfaceMethodName)
442 .ldc(interfaceMethodType.toMethodDescriptorString())
443 .ldc(implInfo.getReferenceKind())
444 .ldc(implInfo.getDeclaringClass().getName().replace('.', '/'))
445 .ldc(implInfo.getName())
446 .ldc(implInfo.getMethodType().toMethodDescriptorString())
447 .ldc(dynamicMethodType.toMethodDescriptorString())
448 .loadConstant(argDescs.length)
449 .anewarray(CD_Object);
450 for (int i = 0; i < argDescs.length; i++) {
451 cob.dup()
452 .loadConstant(i)
453 .aload(0)
454 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
455 TypeConvertingMethodAdapter.boxIfTypePrimitive(cob, TypeKind.from(argDescs[i]));
456 cob.aastore();
457 }
458 cob.invokespecial(SerializationSupport.CD_SerializedLambda, INIT_NAME,
459 SerializationSupport.MTD_CTOR_SERIALIZED_LAMBDA)
460 .areturn();
461 }
462 });
463 }
464
465 /**
466 * Generate a readObject/writeObject method that is hostile to serialization
467 */
468 private void generateSerializationHostileMethods(ClassBuilder clb) {
469 var hostileMethod = new Consumer<MethodBuilder>() {
470 @Override
471 public void accept(MethodBuilder mb) {
472 ConstantPoolBuilder cp = mb.constantPool();
473 ClassEntry nseCE = cp.classEntry(SerializationSupport.CD_NotSerializableException);
474 mb.with(ExceptionsAttribute.of(nseCE))
475 .withCode(new Consumer<CodeBuilder>() {
476 @Override
477 public void accept(CodeBuilder cob) {
478 cob.new_(nseCE)
479 .dup()
480 .ldc("Non-serializable lambda")
481 .invokespecial(cp.methodRefEntry(nseCE, cp.nameAndTypeEntry(INIT_NAME,
482 SerializationSupport.MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION)))
483 .athrow();
484 }
485 });
486 }
487 };
488 clb.withMethod(SerializationSupport.NAME_METHOD_WRITE_OBJECT, SerializationSupport.MTD_void_ObjectOutputStream,
489 ACC_PRIVATE + ACC_FINAL, hostileMethod);
490 clb.withMethod(SerializationSupport.NAME_METHOD_READ_OBJECT, SerializationSupport.MTD_void_ObjectInputStream,
491 ACC_PRIVATE + ACC_FINAL, hostileMethod);
492 }
493
494 /**
495 * This method generates a method body which calls the lambda implementation
496 * method, converting arguments, as needed.
497 */
498 Consumer<CodeBuilder> forwardingMethod(MethodType methodType) {
499 return new Consumer<>() {
500 @Override
501 public void accept(CodeBuilder cob) {
502 if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
503 cob.new_(implMethodClassDesc)
504 .dup();
505 }
506 if (useImplMethodHandle) {
507 ConstantPoolBuilder cp = cob.constantPool();
508 cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA), List.of()),
509 cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
510 }
511 for (int i = 0; i < argDescs.length; i++) {
512 cob.aload(0)
513 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
514 }
515
516 convertArgumentTypes(cob, methodType);
517
518 if (useImplMethodHandle) {
519 MethodType mtype = implInfo.getMethodType();
520 if (implKind != MethodHandleInfo.REF_invokeStatic) {
521 mtype = mtype.insertParameterTypes(0, implClass);
522 }
523 cob.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(mtype));
524 } else {
525 // Invoke the method we want to forward to
526 cob.invoke(invocationOpcode(), implMethodClassDesc, implMethodName, implMethodDesc, implClass.isInterface());
527 }
528 // Convert the return value (if any) and return it
529 // Note: if adapting from non-void to void, the 'return'
530 // instruction will pop the unneeded result
531 Class<?> implReturnClass = implMethodType.returnType();
532 Class<?> samReturnClass = methodType.returnType();
533 TypeConvertingMethodAdapter.convertType(cob, implReturnClass, samReturnClass, samReturnClass);
534 cob.return_(TypeKind.from(samReturnClass));
535 }
536 };
537 }
538
539 private void convertArgumentTypes(CodeBuilder cob, MethodType samType) {
540 int samParametersLength = samType.parameterCount();
541 int captureArity = factoryType.parameterCount();
542 for (int i = 0; i < samParametersLength; i++) {
543 Class<?> argType = samType.parameterType(i);
544 cob.loadLocal(TypeKind.from(argType), cob.parameterSlot(i));
545 TypeConvertingMethodAdapter.convertType(cob, argType, implMethodType.parameterType(captureArity + i), dynamicMethodType.parameterType(i));
546 }
547 }
548
549 private Opcode invocationOpcode() throws InternalError {
550 return switch (implKind) {
551 case MethodHandleInfo.REF_invokeStatic -> Opcode.INVOKESTATIC;
552 case MethodHandleInfo.REF_newInvokeSpecial -> Opcode.INVOKESPECIAL;
553 case MethodHandleInfo.REF_invokeVirtual -> Opcode.INVOKEVIRTUAL;
554 case MethodHandleInfo.REF_invokeInterface -> Opcode.INVOKEINTERFACE;
555 case MethodHandleInfo.REF_invokeSpecial -> Opcode.INVOKESPECIAL;
556 default -> throw new InternalError("Unexpected invocation kind: " + implKind);
557 };
558 }
559
560 static ClassDesc implClassDesc(Class<?> cls) {
561 return cls.isHidden() ? null : ConstantUtils.referenceClassDesc(cls.descriptorString());
562 }
563
564 static ClassDesc classDesc(Class<?> cls) {
565 return cls.isPrimitive() ? Wrapper.forPrimitiveType(cls).basicClassDescriptor()
566 : ConstantUtils.referenceClassDesc(cls.descriptorString());
567 }
568
569 static MethodTypeDesc methodDesc(MethodType mt) {
570 var params = new ClassDesc[mt.parameterCount()];
571 for (int i = 0; i < params.length; i++) {
572 params[i] = classDesc(mt.parameterType(i));
573 }
574 return MethodTypeDescImpl.ofValidated(classDesc(mt.returnType()), params);
575 }
576 }