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.PreviewFeatures;
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.constant.ClassDesc;
42 import java.lang.constant.MethodTypeDesc;
43 import java.lang.reflect.ClassFileFormatVersion;
44 import java.lang.reflect.Modifier;
45 import java.util.LinkedHashSet;
46 import java.util.List;
47 import java.util.Set;
48 import java.util.function.Consumer;
49
50 import static java.lang.classfile.ClassFile.*;
51 import java.lang.classfile.attribute.ExceptionsAttribute;
52 import java.lang.classfile.constantpool.ClassEntry;
53 import java.lang.classfile.constantpool.ConstantPoolBuilder;
54
55 import static java.lang.constant.ConstantDescs.*;
56 import static java.lang.invoke.MethodHandleNatives.Constants.NESTMATE_CLASS;
57 import static java.lang.invoke.MethodHandleNatives.Constants.STRONG_LOADER_LINK;
58 import jdk.internal.constant.ConstantUtils;
59 import jdk.internal.constant.MethodTypeDescImpl;
60 import jdk.internal.vm.annotation.Stable;
61 import sun.invoke.util.Wrapper;
62
63 /**
64 * Lambda metafactory implementation which dynamically creates an
65 * inner-class-like class per lambda callsite.
66 *
67 * @see LambdaMetafactory
68 */
69 /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory {
70 private static final String LAMBDA_INSTANCE_FIELD = "LAMBDA_INSTANCE$";
71 private static final @Stable String[] ARG_NAME_CACHE = {"arg$1", "arg$2", "arg$3", "arg$4", "arg$5", "arg$6", "arg$7", "arg$8"};
72 private static final ClassDesc[] EMPTY_CLASSDESC_ARRAY = ConstantUtils.EMPTY_CLASSDESC;
73
74 // For dumping generated classes to disk, for debugging purposes
75 private static final ClassFileDumper lambdaProxyClassFileDumper;
76
77 private static final boolean disableEagerInitialization;
78
79 static {
80 // To dump the lambda proxy classes, set this system property:
81 // -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles
82 // or -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles=true
83 final String dumpProxyClassesKey = "jdk.invoke.LambdaMetafactory.dumpProxyClassFiles";
84 lambdaProxyClassFileDumper = ClassFileDumper.getInstance(dumpProxyClassesKey, "DUMP_LAMBDA_PROXY_CLASS_FILES");
85
86 final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
87 disableEagerInitialization = Boolean.getBoolean(disableEagerInitializationKey);
88 }
89
90 // See context values in AbstractValidatingLambdaMetafactory
91 private final ClassDesc implMethodClassDesc; // Name of type containing implementation "CC"
92 private final String implMethodName; // Name of implementation method "impl"
93 private final MethodTypeDesc implMethodDesc; // Type descriptor for implementation methods "(I)Ljava/lang/String;"
94 private final MethodType constructorType; // Generated class constructor type "(CC)void"
95 private final MethodTypeDesc constructorTypeDesc;// Type descriptor for the generated class constructor type "(CC)void"
96 private final ClassDesc[] argDescs; // Type descriptors for the constructor arguments
97 private final String lambdaClassName; // Generated name for the generated class "X$$Lambda$1"
98 private final ConstantPoolBuilder pool = ConstantPoolBuilder.of();
99 private final ClassEntry lambdaClassEntry; // Class entry for the generated class "X$$Lambda$1"
100 private final boolean useImplMethodHandle; // use MethodHandle invocation instead of symbolic bytecode invocation
101
102 /**
103 * General meta-factory constructor, supporting both standard cases and
104 * allowing for uncommon options such as serialization or bridging.
105 *
106 * @param caller Stacked automatically by VM; represents a lookup context
107 * with the accessibility privileges of the caller.
108 * @param factoryType Stacked automatically by VM; the signature of the
109 * invoked method, which includes the expected static
110 * type of the returned lambda object, and the static
111 * types of the captured arguments for the lambda. In
112 * the event that the implementation method is an
113 * instance method, the first argument in the invocation
114 * signature will correspond to the receiver.
115 * @param interfaceMethodName Name of the method in the functional interface to
116 * which the lambda or method reference is being
117 * converted, represented as a String.
118 * @param interfaceMethodType Type of the method in the functional interface to
119 * which the lambda or method reference is being
120 * converted, represented as a MethodType.
121 * @param implementation The implementation method which should be called (with
122 * suitable adaptation of argument types, return types,
123 * and adjustment for captured arguments) when methods of
124 * the resulting functional interface instance are invoked.
125 * @param dynamicMethodType The signature of the primary functional
126 * interface method after type variables are
127 * substituted with their instantiation from
128 * the capture site
129 * @param isSerializable Should the lambda be made serializable? If set,
130 * either the target type or one of the additional SAM
131 * types must extend {@code Serializable}.
132 * @param altInterfaces Additional interfaces which the lambda object
133 * should implement.
134 * @param altMethods Method types for additional signatures to be
135 * implemented by invoking the implementation method
136 * @throws LambdaConversionException If any of the meta-factory protocol
137 * invariants are violated
138 */
139 public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
140 MethodType factoryType,
141 String interfaceMethodName,
142 MethodType interfaceMethodType,
143 MethodHandle implementation,
144 MethodType dynamicMethodType,
145 boolean isSerializable,
146 Class<?>[] altInterfaces,
147 MethodType[] altMethods)
148 throws LambdaConversionException {
149 super(caller, factoryType, interfaceMethodName, interfaceMethodType,
150 implementation, dynamicMethodType,
151 isSerializable, altInterfaces, altMethods);
152 implMethodClassDesc = implClassDesc(implClass);
153 implMethodName = implInfo.getName();
154 implMethodDesc = methodDesc(implInfo.getMethodType());
155 constructorType = factoryType.changeReturnType(Void.TYPE);
156 lambdaClassName = lambdaClassName(targetClass);
157 lambdaClassEntry = pool.classEntry(ConstantUtils.internalNameToDesc(lambdaClassName));
158 // If the target class invokes a protected method inherited from a
159 // superclass in a different package, or does 'invokespecial', the
160 // lambda class has no access to the resolved method, or does
161 // 'invokestatic' on a hidden class which cannot be resolved by name.
162 // Instead, we need to pass the live implementation method handle to
163 // the proxy class to invoke directly. (javac prefers to avoid this
164 // situation by generating bridges in the target class)
165 useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
166 !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
167 implKind == MethodHandleInfo.REF_invokeSpecial ||
168 implKind == MethodHandleInfo.REF_invokeStatic && implClass.isHidden();
169 int parameterCount = factoryType.parameterCount();
170 ClassDesc[] argDescs;
171 MethodTypeDesc constructorTypeDesc;
172 if (parameterCount > 0) {
173 argDescs = new ClassDesc[parameterCount];
174 for (int i = 0; i < parameterCount; i++) {
175 argDescs[i] = classDesc(factoryType.parameterType(i));
176 }
177 constructorTypeDesc = MethodTypeDescImpl.ofValidated(CD_void, argDescs);
178 } else {
179 argDescs = EMPTY_CLASSDESC_ARRAY;
180 constructorTypeDesc = MTD_void;
181 }
182 this.argDescs = argDescs;
183 this.constructorTypeDesc = constructorTypeDesc;
184 }
185
186 private static String argName(int i) {
187 return i < ARG_NAME_CACHE.length ? ARG_NAME_CACHE[i] : "arg$" + (i + 1);
188 }
189
190 private static String sanitizedTargetClassName(Class<?> targetClass) {
191 String name = targetClass.getName();
192 if (targetClass.isHidden()) {
193 // use the original class name
194 name = name.replace('/', '_');
195 }
196 return name.replace('.', '/');
197 }
198
199 private static String lambdaClassName(Class<?> targetClass) {
200 return sanitizedTargetClassName(targetClass).concat("$$Lambda");
201 }
202
203 /**
204 * Build the CallSite. Generate a class file which implements the functional
205 * interface, define the class, if there are no parameters create an instance
206 * of the class which the CallSite will return, otherwise, generate handles
207 * which will call the class' constructor.
208 *
209 * @return a CallSite, which, when invoked, will return an instance of the
210 * functional interface
211 * @throws LambdaConversionException If properly formed functional interface
212 * is not found
213 */
214 @Override
215 CallSite buildCallSite() throws LambdaConversionException {
216 final Class<?> innerClass = spinInnerClass();
217 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
218 try {
219 return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
220 factoryType.returnType()));
221 } catch (ReflectiveOperationException e) {
222 throw new LambdaConversionException(
223 "Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e);
224 }
225 } else {
226 try {
227 MethodHandle mh = caller.findConstructor(innerClass, constructorType);
228 if (factoryType.parameterCount() == 0) {
229 // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance
230 Object inst = mh.invokeBasic();
231 return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
232 } else {
233 return new ConstantCallSite(mh.asType(factoryType));
234 }
235 } catch (ReflectiveOperationException e) {
236 throw new LambdaConversionException("Exception finding constructor", e);
237 } catch (Throwable e) {
238 throw new LambdaConversionException("Exception instantiating lambda object", e);
239 }
240 }
241 }
242
243 /**
244 * Spins the lambda proxy class.
245 *
246 * This first checks if a lambda proxy class can be loaded from CDS archive.
247 * Otherwise, generate the lambda proxy class. If CDS dumping is enabled, it
248 * registers the lambda proxy class for including into the CDS archive.
249 */
250 private Class<?> spinInnerClass() throws LambdaConversionException {
251 // CDS does not handle disableEagerInitialization or useImplMethodHandle
252 if (!disableEagerInitialization && !useImplMethodHandle) {
253 if (CDS.isUsingArchive()) {
254 // load from CDS archive if present
255 Class<?> innerClass = LambdaProxyClassArchive.find(targetClass,
256 interfaceMethodName,
257 factoryType,
258 interfaceMethodType,
259 implementation,
260 dynamicMethodType,
261 isSerializable,
262 altInterfaces,
263 altMethods);
264 if (innerClass != null) return innerClass;
265 }
266
267 // include lambda proxy class in CDS archive at dump time
268 if (CDS.isDumpingArchive()) {
269 Class<?> innerClass = generateInnerClass();
270 LambdaProxyClassArchive.register(targetClass,
271 interfaceMethodName,
272 factoryType,
273 interfaceMethodType,
274 implementation,
275 dynamicMethodType,
276 isSerializable,
277 altInterfaces,
278 altMethods,
279 innerClass);
280 return innerClass;
281 }
282
283 }
284 return generateInnerClass();
285 }
286
287 /**
288 * Generate a class file which implements the functional
289 * interface, define and return the class.
290 *
291 * @return a Class which implements the functional interface
292 * @throws LambdaConversionException If properly formed functional interface
293 * is not found
294 */
295 private Class<?> generateInnerClass() throws LambdaConversionException {
296 List<ClassDesc> interfaces;
297 ClassDesc interfaceDesc = classDesc(interfaceClass);
298 boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
299 if (altInterfaces.length == 0) {
300 interfaces = List.of(interfaceDesc);
301 } else {
302 // Assure no duplicate interfaces (ClassFormatError)
303 Set<ClassDesc> itfs = LinkedHashSet.newLinkedHashSet(altInterfaces.length + 1);
304 itfs.add(interfaceDesc);
305 for (Class<?> i : altInterfaces) {
306 itfs.add(classDesc(i));
307 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
308 }
309 interfaces = List.copyOf(itfs);
310 }
311 final boolean finalAccidentallySerializable = accidentallySerializable;
312 final byte[] classBytes = ClassFile.of().build(lambdaClassEntry, pool, new Consumer<ClassBuilder>() {
313 @Override
314 public void accept(ClassBuilder clb) {
315 clb.withVersion(ClassFileFormatVersion.latest().major(), (PreviewFeatures.isEnabled() ? ClassFile.PREVIEW_MINOR_VERSION : 0))
316 .withFlags(ACC_SUPER | ACC_FINAL | ACC_SYNTHETIC)
317 .withInterfaceSymbols(interfaces);
318 // All Classes in the BSM argument method types are loaded; no need for LoadableDescriptors
319
320 // Generate final fields to be filled in by constructor
321 for (int i = 0; i < argDescs.length; i++) {
322 clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
323 }
324
325 generateConstructor(clb);
326
327 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
328 generateClassInitializer(clb);
329 }
330
331 // Forward the SAM method
332 clb.withMethodBody(interfaceMethodName,
333 methodDesc(interfaceMethodType),
334 ACC_PUBLIC,
335 forwardingMethod(interfaceMethodType));
336
337 // Forward the bridges
338 if (altMethods != null) {
339 for (MethodType mt : altMethods) {
340 clb.withMethodBody(interfaceMethodName,
341 methodDesc(mt),
342 ACC_PUBLIC | ACC_BRIDGE,
343 forwardingMethod(mt));
344 }
345 }
346
347 if (isSerializable)
348 generateSerializationFriendlyMethods(clb);
349 else if (finalAccidentallySerializable)
350 generateSerializationHostileMethods(clb);
351 }
352 });
353
354 // Define the generated class in this VM.
355
356 try {
357 // this class is linked at the indy callsite; so define a hidden nestmate
358 var classdata = useImplMethodHandle? implementation : null;
359 return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, NESTMATE_CLASS | STRONG_LOADER_LINK)
360 .defineClass(!disableEagerInitialization, classdata);
361
362 } catch (Throwable t) {
363 throw new InternalError(t);
364 }
365 }
366
367 /**
368 * Generate a static field and a static initializer that sets this field to an instance of the lambda
369 */
370 private void generateClassInitializer(ClassBuilder clb) {
371 ClassDesc lambdaTypeDescriptor = classDesc(factoryType.returnType());
372
373 // Generate the static final field that holds the lambda singleton
374 clb.withField(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
375
376 // Instantiate the lambda and store it to the static final field
377 clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, new Consumer<>() {
378 @Override
379 public void accept(CodeBuilder cob) {
380 assert factoryType.parameterCount() == 0;
381 cob.new_(lambdaClassEntry)
382 .dup()
383 .invokespecial(pool.methodRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(INIT_NAME, constructorTypeDesc)))
384 .putstatic(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor)))
385 .return_();
386 }
387 });
388 }
389
390 /**
391 * Generate the constructor for the class
392 */
393 private void generateConstructor(ClassBuilder clb) {
394 // Generate constructor
395 clb.withMethodBody(INIT_NAME, constructorTypeDesc, ACC_PRIVATE,
396 new Consumer<>() {
397 @Override
398 public void accept(CodeBuilder cob) {
399 int parameterCount = factoryType.parameterCount();
400 for (int i = 0; i < parameterCount; i++) {
401 cob.aload(0)
402 .loadLocal(TypeKind.from(factoryType.parameterType(i)), cob.parameterSlot(i))
403 .putfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
404 }
405 cob.aload(0)
406 .invokespecial(CD_Object, INIT_NAME, MTD_void)
407 .return_();
408 }
409 });
410 }
411
412 private static class SerializationSupport {
413 // Serialization support
414 private static final ClassDesc CD_SerializedLambda = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/invoke/SerializedLambda;");
415 private static final ClassDesc CD_ObjectOutputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectOutputStream;");
416 private static final ClassDesc CD_ObjectInputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectInputStream;");
417 private static final MethodTypeDesc MTD_Object = MethodTypeDescImpl.ofValidated(CD_Object);
418 private static final MethodTypeDesc MTD_void_ObjectOutputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectOutputStream);
419 private static final MethodTypeDesc MTD_void_ObjectInputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectInputStream);
420
421 private static final String NAME_METHOD_WRITE_REPLACE = "writeReplace";
422 private static final String NAME_METHOD_READ_OBJECT = "readObject";
423 private static final String NAME_METHOD_WRITE_OBJECT = "writeObject";
424
425 static final ClassDesc CD_NotSerializableException = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/NotSerializableException;");
426 static final MethodTypeDesc MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION = MethodTypeDescImpl.ofValidated(CD_void, CD_String);
427 static final MethodTypeDesc MTD_CTOR_SERIALIZED_LAMBDA = MethodTypeDescImpl.ofValidated(CD_void,
428 CD_Class, CD_String, CD_String, CD_String, CD_int, CD_String, CD_String, CD_String, CD_String, ConstantUtils.CD_Object_array);
429
430 }
431
432 /**
433 * Generate a writeReplace method that supports serialization
434 */
435 private void generateSerializationFriendlyMethods(ClassBuilder clb) {
436 clb.withMethodBody(SerializationSupport.NAME_METHOD_WRITE_REPLACE, SerializationSupport.MTD_Object, ACC_PRIVATE | ACC_FINAL,
437 new Consumer<>() {
438 @Override
439 public void accept(CodeBuilder cob) {
440 cob.new_(SerializationSupport.CD_SerializedLambda)
441 .dup()
442 .ldc(ClassDesc.ofInternalName(sanitizedTargetClassName(targetClass)))
443 .ldc(factoryType.returnType().getName().replace('.', '/'))
444 .ldc(interfaceMethodName)
445 .ldc(interfaceMethodType.toMethodDescriptorString())
446 .ldc(implInfo.getReferenceKind())
447 .ldc(implInfo.getDeclaringClass().getName().replace('.', '/'))
448 .ldc(implInfo.getName())
449 .ldc(implInfo.getMethodType().toMethodDescriptorString())
450 .ldc(dynamicMethodType.toMethodDescriptorString())
451 .loadConstant(argDescs.length)
452 .anewarray(CD_Object);
453 for (int i = 0; i < argDescs.length; i++) {
454 cob.dup()
455 .loadConstant(i)
456 .aload(0)
457 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
458 TypeConvertingMethodAdapter.boxIfTypePrimitive(cob, TypeKind.from(argDescs[i]));
459 cob.aastore();
460 }
461 cob.invokespecial(SerializationSupport.CD_SerializedLambda, INIT_NAME,
462 SerializationSupport.MTD_CTOR_SERIALIZED_LAMBDA)
463 .areturn();
464 }
465 });
466 }
467
468 /**
469 * Generate a readObject/writeObject method that is hostile to serialization
470 */
471 private void generateSerializationHostileMethods(ClassBuilder clb) {
472 var hostileMethod = new Consumer<MethodBuilder>() {
473 @Override
474 public void accept(MethodBuilder mb) {
475 ConstantPoolBuilder cp = mb.constantPool();
476 ClassEntry nseCE = cp.classEntry(SerializationSupport.CD_NotSerializableException);
477 mb.with(ExceptionsAttribute.of(nseCE))
478 .withCode(new Consumer<CodeBuilder>() {
479 @Override
480 public void accept(CodeBuilder cob) {
481 cob.new_(nseCE)
482 .dup()
483 .ldc("Non-serializable lambda")
484 .invokespecial(cp.methodRefEntry(nseCE, cp.nameAndTypeEntry(INIT_NAME,
485 SerializationSupport.MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION)))
486 .athrow();
487 }
488 });
489 }
490 };
491 clb.withMethod(SerializationSupport.NAME_METHOD_WRITE_OBJECT, SerializationSupport.MTD_void_ObjectOutputStream,
492 ACC_PRIVATE + ACC_FINAL, hostileMethod);
493 clb.withMethod(SerializationSupport.NAME_METHOD_READ_OBJECT, SerializationSupport.MTD_void_ObjectInputStream,
494 ACC_PRIVATE + ACC_FINAL, hostileMethod);
495 }
496
497 /**
498 * This method generates a method body which calls the lambda implementation
499 * method, converting arguments, as needed.
500 */
501 Consumer<CodeBuilder> forwardingMethod(MethodType methodType) {
502 return new Consumer<>() {
503 @Override
504 public void accept(CodeBuilder cob) {
505 if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
506 cob.new_(implMethodClassDesc)
507 .dup();
508 }
509 if (useImplMethodHandle) {
510 ConstantPoolBuilder cp = cob.constantPool();
511 cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA), List.of()),
512 cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
513 }
514 for (int i = 0; i < argDescs.length; i++) {
515 cob.aload(0)
516 .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
517 }
518
519 convertArgumentTypes(cob, methodType);
520
521 if (useImplMethodHandle) {
522 MethodType mtype = implInfo.getMethodType();
523 if (implKind != MethodHandleInfo.REF_invokeStatic) {
524 mtype = mtype.insertParameterTypes(0, implClass);
525 }
526 cob.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(mtype));
527 } else {
528 // Invoke the method we want to forward to
529 cob.invoke(invocationOpcode(), implMethodClassDesc, implMethodName, implMethodDesc, implClass.isInterface());
530 }
531 // Convert the return value (if any) and return it
532 // Note: if adapting from non-void to void, the 'return'
533 // instruction will pop the unneeded result
534 Class<?> implReturnClass = implMethodType.returnType();
535 Class<?> samReturnClass = methodType.returnType();
536 TypeConvertingMethodAdapter.convertType(cob, implReturnClass, samReturnClass, samReturnClass);
537 cob.return_(TypeKind.from(samReturnClass));
538 }
539 };
540 }
541
542 private void convertArgumentTypes(CodeBuilder cob, MethodType samType) {
543 int samParametersLength = samType.parameterCount();
544 int captureArity = factoryType.parameterCount();
545 for (int i = 0; i < samParametersLength; i++) {
546 Class<?> argType = samType.parameterType(i);
547 cob.loadLocal(TypeKind.from(argType), cob.parameterSlot(i));
548 TypeConvertingMethodAdapter.convertType(cob, argType, implMethodType.parameterType(captureArity + i), dynamicMethodType.parameterType(i));
549 }
550 }
551
552 private Opcode invocationOpcode() throws InternalError {
553 return switch (implKind) {
554 case MethodHandleInfo.REF_invokeStatic -> Opcode.INVOKESTATIC;
555 case MethodHandleInfo.REF_newInvokeSpecial -> Opcode.INVOKESPECIAL;
556 case MethodHandleInfo.REF_invokeVirtual -> Opcode.INVOKEVIRTUAL;
557 case MethodHandleInfo.REF_invokeInterface -> Opcode.INVOKEINTERFACE;
558 case MethodHandleInfo.REF_invokeSpecial -> Opcode.INVOKESPECIAL;
559 default -> throw new InternalError("Unexpected invocation kind: " + implKind);
560 };
561 }
562
563 static ClassDesc implClassDesc(Class<?> cls) {
564 return cls.isHidden() ? null : ConstantUtils.referenceClassDesc(cls.descriptorString());
565 }
566
567 static ClassDesc classDesc(Class<?> cls) {
568 return cls.isPrimitive() ? Wrapper.forPrimitiveType(cls).basicClassDescriptor()
569 : ConstantUtils.referenceClassDesc(cls.descriptorString());
570 }
571
572 static MethodTypeDesc methodDesc(MethodType mt) {
573 var params = new ClassDesc[mt.parameterCount()];
574 for (int i = 0; i < params.length; i++) {
575 params[i] = classDesc(mt.parameterType(i));
576 }
577 return MethodTypeDescImpl.ofValidated(classDesc(mt.returnType()), params);
578 }
579 }