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