1 /*
  2  * Copyright (c) 2012, 2024, 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                 // Generate final fields to be filled in by constructor
323                 for (int i = 0; i < argDescs.length; i++) {
324                     clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
325                 }
326 
327                 generateConstructor(clb);
328 
329                 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
330                     generateClassInitializer(clb);
331                 }
332 
333                 // Forward the SAM method
334                 clb.withMethodBody(interfaceMethodName,
335                         methodDesc(interfaceMethodType),
336                         ACC_PUBLIC,
337                         forwardingMethod(interfaceMethodType));
338 
339                 // Forward the bridges
340                 if (altMethods != null) {
341                     for (MethodType mt : altMethods) {
342                         clb.withMethodBody(interfaceMethodName,
343                                 methodDesc(mt),
344                                 ACC_PUBLIC | ACC_BRIDGE,
345                                 forwardingMethod(mt));
346                     }
347                 }
348 
349                 if (isSerializable)
350                     generateSerializationFriendlyMethods(clb);
351                 else if (finalAccidentallySerializable)
352                     generateSerializationHostileMethods(clb);
353 
354                 if (finisher != null) {
355                     additionalClassDataHolder[0] = finisher.apply(clb);
356                 }
357             }
358         });
359 
360         // Define the generated class in this VM.
361 
362         try {
363             // this class is linked at the indy callsite; so define a hidden nestmate
364             var additionalClassData = additionalClassDataHolder[0];
365             var classdata = additionalClassData == null
366                     ? useImplMethodHandle ? List.of(implementation) : null
367                     : useImplMethodHandle ? List.of(implementation, additionalClassData) : List.of(additionalClassData);
368             return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, NESTMATE_CLASS | STRONG_LOADER_LINK)
369                          .defineClass(!disableEagerInitialization, classdata);
370 
371         } catch (Throwable t) {
372             throw new InternalError(t);
373         }
374     }
375 
376     /**
377      * Generate a static field and a static initializer that sets this field to an instance of the lambda
378      */
379     private void generateClassInitializer(ClassBuilder clb) {
380         ClassDesc lambdaTypeDescriptor = classDesc(factoryType.returnType());
381 
382         // Generate the static final field that holds the lambda singleton
383         clb.withField(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
384 
385         // Instantiate the lambda and store it to the static final field
386         clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, new Consumer<>() {
387             @Override
388             public void accept(CodeBuilder cob) {
389                 assert factoryType.parameterCount() == 0;
390                 cob.new_(lambdaClassEntry)
391                    .dup()
392                    .invokespecial(pool.methodRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(INIT_NAME, constructorTypeDesc)))
393                    .putstatic(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor)))
394                    .return_();
395             }
396         });
397     }
398 
399     /**
400      * Generate the constructor for the class
401      */
402     private void generateConstructor(ClassBuilder clb) {
403         // Generate constructor
404         clb.withMethodBody(INIT_NAME, constructorTypeDesc, ACC_PRIVATE,
405                 new Consumer<>() {
406                     @Override
407                     public void accept(CodeBuilder cob) {
408                         cob.aload(0)
409                            .invokespecial(CD_Object, INIT_NAME, MTD_void);
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.return_();
417                     }
418                 });
419     }
420 
421     private static class SerializationSupport {
422         // Serialization support
423         private static final ClassDesc CD_SerializedLambda = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/invoke/SerializedLambda;");
424         private static final ClassDesc CD_ObjectOutputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectOutputStream;");
425         private static final ClassDesc CD_ObjectInputStream = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/ObjectInputStream;");
426         private static final MethodTypeDesc MTD_Object = MethodTypeDescImpl.ofValidated(CD_Object);
427         private static final MethodTypeDesc MTD_void_ObjectOutputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectOutputStream);
428         private static final MethodTypeDesc MTD_void_ObjectInputStream = MethodTypeDescImpl.ofValidated(CD_void, CD_ObjectInputStream);
429 
430         private static final String NAME_METHOD_WRITE_REPLACE = "writeReplace";
431         private static final String NAME_METHOD_READ_OBJECT = "readObject";
432         private static final String NAME_METHOD_WRITE_OBJECT = "writeObject";
433 
434         static final ClassDesc CD_NotSerializableException = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/NotSerializableException;");
435         static final MethodTypeDesc MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION = MethodTypeDescImpl.ofValidated(CD_void, CD_String);
436         static final MethodTypeDesc MTD_CTOR_SERIALIZED_LAMBDA = MethodTypeDescImpl.ofValidated(CD_void,
437                 CD_Class, CD_String, CD_String, CD_String, CD_int, CD_String, CD_String, CD_String, CD_String, ConstantUtils.CD_Object_array);
438 
439     }
440 
441     /**
442      * Generate a writeReplace method that supports serialization
443      */
444     private void generateSerializationFriendlyMethods(ClassBuilder clb) {
445         clb.withMethodBody(SerializationSupport.NAME_METHOD_WRITE_REPLACE, SerializationSupport.MTD_Object, ACC_PRIVATE | ACC_FINAL,
446                 new Consumer<>() {
447                     @Override
448                     public void accept(CodeBuilder cob) {
449                         cob.new_(SerializationSupport.CD_SerializedLambda)
450                            .dup()
451                            .ldc(ClassDesc.ofInternalName(sanitizedTargetClassName(targetClass)))
452                            .ldc(factoryType.returnType().getName().replace('.', '/'))
453                            .ldc(interfaceMethodName)
454                            .ldc(interfaceMethodType.toMethodDescriptorString())
455                            .ldc(implInfo.getReferenceKind())
456                            .ldc(implInfo.getDeclaringClass().getName().replace('.', '/'))
457                            .ldc(implInfo.getName())
458                            .ldc(implInfo.getMethodType().toMethodDescriptorString())
459                            .ldc(dynamicMethodType.toMethodDescriptorString())
460                            .loadConstant(argDescs.length)
461                            .anewarray(CD_Object);
462                         for (int i = 0; i < argDescs.length; i++) {
463                             cob.dup()
464                                .loadConstant(i)
465                                .aload(0)
466                                .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
467                             TypeConvertingMethodAdapter.boxIfTypePrimitive(cob, TypeKind.from(argDescs[i]));
468                             cob.aastore();
469                         }
470                         cob.invokespecial(SerializationSupport.CD_SerializedLambda, INIT_NAME,
471                                           SerializationSupport.MTD_CTOR_SERIALIZED_LAMBDA)
472                            .areturn();
473                     }
474                 });
475     }
476 
477     /**
478      * Generate a readObject/writeObject method that is hostile to serialization
479      */
480     private void generateSerializationHostileMethods(ClassBuilder clb) {
481         var hostileMethod = new Consumer<MethodBuilder>() {
482             @Override
483             public void accept(MethodBuilder mb) {
484                 ConstantPoolBuilder cp = mb.constantPool();
485                 ClassEntry nseCE = cp.classEntry(SerializationSupport.CD_NotSerializableException);
486                 mb.with(ExceptionsAttribute.of(nseCE))
487                         .withCode(new Consumer<CodeBuilder>() {
488                             @Override
489                             public void accept(CodeBuilder cob) {
490                                 cob.new_(nseCE)
491                                         .dup()
492                                         .ldc("Non-serializable lambda")
493                                         .invokespecial(cp.methodRefEntry(nseCE, cp.nameAndTypeEntry(INIT_NAME,
494                                                 SerializationSupport.MTD_CTOR_NOT_SERIALIZABLE_EXCEPTION)))
495                                         .athrow();
496                             }
497                         });
498             }
499         };
500         clb.withMethod(SerializationSupport.NAME_METHOD_WRITE_OBJECT, SerializationSupport.MTD_void_ObjectOutputStream,
501                 ACC_PRIVATE + ACC_FINAL, hostileMethod);
502         clb.withMethod(SerializationSupport.NAME_METHOD_READ_OBJECT, SerializationSupport.MTD_void_ObjectInputStream,
503                 ACC_PRIVATE + ACC_FINAL, hostileMethod);
504     }
505 
506     /**
507      * This method generates a method body which calls the lambda implementation
508      * method, converting arguments, as needed.
509      */
510     Consumer<CodeBuilder> forwardingMethod(MethodType methodType) {
511         return new Consumer<>() {
512             @Override
513             public void accept(CodeBuilder cob) {
514                 if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
515                     cob.new_(implMethodClassDesc)
516                        .dup();
517                 }
518                 if (useImplMethodHandle) {
519                     ConstantPoolBuilder cp = cob.constantPool();
520                     cob.ldc(cp.constantDynamicEntry(cp.bsmEntry(cp.methodHandleEntry(BSM_CLASS_DATA_AT), List.of(cp.intEntry(0))),
521                                                     cp.nameAndTypeEntry(DEFAULT_NAME, CD_MethodHandle)));
522                 }
523                 for (int i = 0; i < argDescs.length; i++) {
524                     cob.aload(0)
525                        .getfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
526                 }
527 
528                 convertArgumentTypes(cob, methodType);
529 
530                 if (useImplMethodHandle) {
531                     MethodType mtype = implInfo.getMethodType();
532                     if (implKind != MethodHandleInfo.REF_invokeStatic) {
533                         mtype = mtype.insertParameterTypes(0, implClass);
534                     }
535                     cob.invokevirtual(CD_MethodHandle, "invokeExact", methodDesc(mtype));
536                 } else {
537                     // Invoke the method we want to forward to
538                     cob.invoke(invocationOpcode(), implMethodClassDesc, implMethodName, implMethodDesc, implClass.isInterface());
539                 }
540                 // Convert the return value (if any) and return it
541                 // Note: if adapting from non-void to void, the 'return'
542                 // instruction will pop the unneeded result
543                 Class<?> implReturnClass = implMethodType.returnType();
544                 Class<?> samReturnClass = methodType.returnType();
545                 TypeConvertingMethodAdapter.convertType(cob, implReturnClass, samReturnClass, samReturnClass);
546                 cob.return_(TypeKind.from(samReturnClass));
547             }
548         };
549     }
550 
551     private void convertArgumentTypes(CodeBuilder cob, MethodType samType) {
552         int samParametersLength = samType.parameterCount();
553         int captureArity = factoryType.parameterCount();
554         for (int i = 0; i < samParametersLength; i++) {
555             Class<?> argType = samType.parameterType(i);
556             cob.loadLocal(TypeKind.from(argType), cob.parameterSlot(i));
557             TypeConvertingMethodAdapter.convertType(cob, argType, implMethodType.parameterType(captureArity + i), dynamicMethodType.parameterType(i));
558         }
559     }
560 
561     private Opcode invocationOpcode() throws InternalError {
562         return switch (implKind) {
563             case MethodHandleInfo.REF_invokeStatic     -> Opcode.INVOKESTATIC;
564             case MethodHandleInfo.REF_newInvokeSpecial -> Opcode.INVOKESPECIAL;
565             case MethodHandleInfo.REF_invokeVirtual    -> Opcode.INVOKEVIRTUAL;
566             case MethodHandleInfo.REF_invokeInterface  -> Opcode.INVOKEINTERFACE;
567             case MethodHandleInfo.REF_invokeSpecial    -> Opcode.INVOKESPECIAL;
568             default -> throw new InternalError("Unexpected invocation kind: " + implKind);
569         };
570     }
571 
572     static ClassDesc implClassDesc(Class<?> cls) {
573         return cls.isHidden() ? null : ConstantUtils.referenceClassDesc(cls.descriptorString());
574     }
575 
576     static ClassDesc classDesc(Class<?> cls) {
577         return cls.isPrimitive() ? Wrapper.forPrimitiveType(cls).basicClassDescriptor()
578                                  : ConstantUtils.referenceClassDesc(cls.descriptorString());
579     }
580 
581     static MethodTypeDesc methodDesc(MethodType mt) {
582         var params = new ClassDesc[mt.parameterCount()];
583         for (int i = 0; i < params.length; i++) {
584             params[i] = classDesc(mt.parameterType(i));
585         }
586         return MethodTypeDescImpl.ofValidated(classDesc(mt.returnType()), params);
587     }
588 }