1 /*
  2  * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.invoke;
 27 
 28 import jdk.internal.access.JavaLangAccess;
 29 import jdk.internal.access.SharedSecrets;
 30 import jdk.internal.constant.ClassOrInterfaceDescImpl;
 31 import jdk.internal.misc.CDS;
 32 import jdk.internal.util.ClassFileDumper;
 33 import sun.invoke.util.VerifyAccess;
 34 
 35 import java.io.Serializable;
 36 import java.lang.classfile.ClassBuilder;
 37 import java.lang.classfile.ClassFile;
 38 import java.lang.classfile.CodeBuilder;
 39 import java.lang.classfile.MethodBuilder;
 40 import java.lang.classfile.Opcode;
 41 import java.lang.classfile.TypeKind;
 42 import java.lang.constant.ClassDesc;
 43 import java.lang.constant.MethodTypeDesc;
 44 import java.lang.reflect.Modifier;
 45 import java.util.LinkedHashSet;
 46 import java.util.List;
 47 import java.util.Set;
 48 import java.util.function.Consumer;
 49 
 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     private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
 75 
 76     // For dumping generated classes to disk, for debugging purposes
 77     private static final ClassFileDumper lambdaProxyClassFileDumper;
 78 
 79     private static final boolean disableEagerInitialization;
 80 
 81     static {
 82         // To dump the lambda proxy classes, set this system property:
 83         //    -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles
 84         // or -Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles=true
 85         final String dumpProxyClassesKey = "jdk.invoke.LambdaMetafactory.dumpProxyClassFiles";
 86         lambdaProxyClassFileDumper = ClassFileDumper.getInstance(dumpProxyClassesKey, "DUMP_LAMBDA_PROXY_CLASS_FILES");
 87 
 88         final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
 89         disableEagerInitialization = Boolean.getBoolean(disableEagerInitializationKey);
 90     }
 91 
 92     // See context values in AbstractValidatingLambdaMetafactory
 93     private final ClassDesc implMethodClassDesc;     // Name of type containing implementation "CC"
 94     private final String implMethodName;             // Name of implementation method "impl"
 95     private final MethodTypeDesc implMethodDesc;     // Type descriptor for implementation methods "(I)Ljava/lang/String;"
 96     private final MethodType constructorType;        // Generated class constructor type "(CC)void"
 97     private final MethodTypeDesc constructorTypeDesc;// Type descriptor for the generated class constructor type "(CC)void"
 98     private final ClassDesc[] argDescs;              // Type descriptors for the constructor arguments
 99     private final String lambdaClassName;            // Generated name for the generated class "X$$Lambda$1"
100     private final ConstantPoolBuilder pool = ConstantPoolBuilder.of();
101     private final ClassEntry lambdaClassEntry;       // Class entry for the generated class "X$$Lambda$1"
102     private final boolean useImplMethodHandle;       // use MethodHandle invocation instead of symbolic bytecode invocation
103 
104     /**
105      * General meta-factory constructor, supporting both standard cases and
106      * allowing for uncommon options such as serialization or bridging.
107      *
108      * @param caller Stacked automatically by VM; represents a lookup context
109      *               with the accessibility privileges of the caller.
110      * @param factoryType Stacked automatically by VM; the signature of the
111      *                    invoked method, which includes the expected static
112      *                    type of the returned lambda object, and the static
113      *                    types of the captured arguments for the lambda.  In
114      *                    the event that the implementation method is an
115      *                    instance method, the first argument in the invocation
116      *                    signature will correspond to the receiver.
117      * @param interfaceMethodName Name of the method in the functional interface to
118      *                   which the lambda or method reference is being
119      *                   converted, represented as a String.
120      * @param interfaceMethodType Type of the method in the functional interface to
121      *                            which the lambda or method reference is being
122      *                            converted, represented as a MethodType.
123      * @param implementation The implementation method which should be called (with
124      *                       suitable adaptation of argument types, return types,
125      *                       and adjustment for captured arguments) when methods of
126      *                       the resulting functional interface instance are invoked.
127      * @param dynamicMethodType The signature of the primary functional
128      *                          interface method after type variables are
129      *                          substituted with their instantiation from
130      *                          the capture site
131      * @param isSerializable Should the lambda be made serializable?  If set,
132      *                       either the target type or one of the additional SAM
133      *                       types must extend {@code Serializable}.
134      * @param altInterfaces Additional interfaces which the lambda object
135      *                      should implement.
136      * @param altMethods Method types for additional signatures to be
137      *                   implemented by invoking the implementation method
138      * @throws LambdaConversionException If any of the meta-factory protocol
139      *         invariants are violated
140      */
141     public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
142                                        MethodType factoryType,
143                                        String interfaceMethodName,
144                                        MethodType interfaceMethodType,
145                                        MethodHandle implementation,
146                                        MethodType dynamicMethodType,
147                                        boolean isSerializable,
148                                        Class<?>[] altInterfaces,
149                                        MethodType[] altMethods)
150             throws LambdaConversionException {
151         super(caller, factoryType, interfaceMethodName, interfaceMethodType,
152               implementation, dynamicMethodType,
153               isSerializable, altInterfaces, altMethods);
154         implMethodClassDesc = implClassDesc(implClass);
155         implMethodName = implInfo.getName();
156         implMethodDesc = methodDesc(implInfo.getMethodType());
157         constructorType = factoryType.changeReturnType(Void.TYPE);
158         lambdaClassName = lambdaClassName(targetClass);
159         lambdaClassEntry = pool.classEntry(ConstantUtils.internalNameToDesc(lambdaClassName));
160         // If the target class invokes a protected method inherited from a
161         // superclass in a different package, or does 'invokespecial', the
162         // lambda class has no access to the resolved method, or does
163         // 'invokestatic' on a hidden class which cannot be resolved by name.
164         // Instead, we need to pass the live implementation method handle to
165         // the proxy class to invoke directly. (javac prefers to avoid this
166         // situation by generating bridges in the target class)
167         useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
168                                !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
169                                implKind == MethodHandleInfo.REF_invokeSpecial ||
170                                implKind == MethodHandleInfo.REF_invokeStatic && implClass.isHidden();
171         int parameterCount = factoryType.parameterCount();
172         ClassDesc[] argDescs;
173         MethodTypeDesc constructorTypeDesc;
174         if (parameterCount > 0) {
175             argDescs = new ClassDesc[parameterCount];
176             for (int i = 0; i < parameterCount; i++) {
177                 argDescs[i] = classDesc(factoryType.parameterType(i));
178             }
179             constructorTypeDesc = MethodTypeDescImpl.ofValidated(CD_void, argDescs);
180         } else {
181             argDescs = EMPTY_CLASSDESC_ARRAY;
182             constructorTypeDesc = MTD_void;
183         }
184         this.argDescs = argDescs;
185         this.constructorTypeDesc = constructorTypeDesc;
186     }
187 
188     private static String argName(int i) {
189         return i < ARG_NAME_CACHE.length ? ARG_NAME_CACHE[i] :  "arg$" + (i + 1);
190     }
191 
192     private static String sanitizedTargetClassName(Class<?> targetClass) {
193         String name = targetClass.getName();
194         if (targetClass.isHidden()) {
195             // use the original class name
196             name = name.replace('/', '_');
197         }
198         return name.replace('.', '/');
199     }
200 
201     private static String lambdaClassName(Class<?> targetClass) {
202         return sanitizedTargetClassName(targetClass).concat("$$Lambda");
203     }
204 
205     /**
206      * Build the CallSite. Generate a class file which implements the functional
207      * interface, define the class, if there are no parameters create an instance
208      * of the class which the CallSite will return, otherwise, generate handles
209      * which will call the class' constructor.
210      *
211      * @return a CallSite, which, when invoked, will return an instance of the
212      * functional interface
213      * @throws LambdaConversionException If properly formed functional interface
214      * is not found
215      */
216     @Override
217     CallSite buildCallSite() throws LambdaConversionException {
218         final Class<?> innerClass = spinInnerClass();
219         if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
220             try {
221                 return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
222                                                                     factoryType.returnType()));
223             } catch (ReflectiveOperationException e) {
224                 throw new LambdaConversionException(
225                         "Exception finding " + LAMBDA_INSTANCE_FIELD + " static field", e);
226             }
227         } else {
228             try {
229                 MethodHandle mh = caller.findConstructor(innerClass, constructorType);
230                 if (factoryType.parameterCount() == 0) {
231                     // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance
232                     Object inst = mh.invokeBasic();
233                     return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
234                 } else {
235                     return new ConstantCallSite(mh.asType(factoryType));
236                 }
237             } catch (ReflectiveOperationException e) {
238                 throw new LambdaConversionException("Exception finding constructor", e);
239             } catch (Throwable e) {
240                 throw new LambdaConversionException("Exception instantiating lambda object", e);
241             }
242         }
243     }
244 
245     /**
246      * Spins the lambda proxy class.
247      *
248      * This first checks if a lambda proxy class can be loaded from CDS archive.
249      * Otherwise, generate the lambda proxy class. If CDS dumping is enabled, it
250      * registers the lambda proxy class for including into the CDS archive.
251      */
252     private Class<?> spinInnerClass() throws LambdaConversionException {
253         // CDS does not handle disableEagerInitialization or useImplMethodHandle
254         if (!disableEagerInitialization && !useImplMethodHandle) {
255             if (CDS.isUsingArchive()) {
256                 // load from CDS archive if present
257                 Class<?> innerClass = LambdaProxyClassArchive.find(targetClass,
258                                                                    interfaceMethodName,
259                                                                    factoryType,
260                                                                    interfaceMethodType,
261                                                                    implementation,
262                                                                    dynamicMethodType,
263                                                                    isSerializable,
264                                                                    altInterfaces,
265                                                                    altMethods);
266                 if (innerClass != null) return innerClass;
267             }
268 
269             // include lambda proxy class in CDS archive at dump time
270             if (CDS.isDumpingArchive()) {
271                 Class<?> innerClass = generateInnerClass();
272                 LambdaProxyClassArchive.register(targetClass,
273                                                  interfaceMethodName,
274                                                  factoryType,
275                                                  interfaceMethodType,
276                                                  implementation,
277                                                  dynamicMethodType,
278                                                  isSerializable,
279                                                  altInterfaces,
280                                                  altMethods,
281                                                  innerClass);
282                 return innerClass;
283             }
284 
285         }
286         return generateInnerClass();
287     }
288 
289     /**
290      * Generate a class file which implements the functional
291      * interface, define and return the class.
292      *
293      * @return a Class which implements the functional interface
294      * @throws LambdaConversionException If properly formed functional interface
295      * is not found
296      */
297     private Class<?> generateInnerClass() throws LambdaConversionException {
298         List<ClassDesc> interfaces;
299         ClassDesc interfaceDesc = classDesc(interfaceClass);
300         boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
301         if (altInterfaces.length == 0) {
302             interfaces = List.of(interfaceDesc);
303         } else {
304             // Assure no duplicate interfaces (ClassFormatError)
305             Set<ClassDesc> itfs = LinkedHashSet.newLinkedHashSet(altInterfaces.length + 1);
306             itfs.add(interfaceDesc);
307             for (Class<?> i : altInterfaces) {
308                 itfs.add(classDesc(i));
309                 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
310             }
311             interfaces = List.copyOf(itfs);
312         }
313         final boolean finalAccidentallySerializable = accidentallySerializable;
314         final byte[] classBytes = ClassFile.of().build(lambdaClassEntry, pool, new Consumer<ClassBuilder>() {
315             @Override
316             public void accept(ClassBuilder clb) {
317                 clb.withFlags(ACC_SUPER | ACC_FINAL | ACC_SYNTHETIC)
318                    .withInterfaceSymbols(interfaces);
319                 // All Classes in the BSM argument method types are loaded; no need for LoadableDescriptors
320 
321                 // Generate final fields to be filled in by constructor
322                 for (int i = 0; i < argDescs.length; i++) {
323                     clb.withField(argName(i), argDescs[i], ACC_PRIVATE | ACC_FINAL);
324                 }
325 
326                 generateConstructor(clb);
327 
328                 if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
329                     generateClassInitializer(clb);
330                 }
331 
332                 // Forward the SAM method
333                 clb.withMethodBody(interfaceMethodName,
334                         methodDesc(interfaceMethodType),
335                         ACC_PUBLIC,
336                         forwardingMethod(interfaceMethodType));
337 
338                 // Forward the bridges
339                 if (altMethods != null) {
340                     for (MethodType mt : altMethods) {
341                         clb.withMethodBody(interfaceMethodName,
342                                 methodDesc(mt),
343                                 ACC_PUBLIC | ACC_BRIDGE,
344                                 forwardingMethod(mt));
345                     }
346                 }
347 
348                 if (isSerializable)
349                     generateSerializationFriendlyMethods(clb);
350                 else if (finalAccidentallySerializable)
351                     generateSerializationHostileMethods(clb);
352             }
353         });
354 
355         // Define the generated class in this VM.
356 
357         try {
358             // This class is linked at the indy callsite; so define a hidden nestmate.
359             // Redefinition or retransformation of the caller can cause lambda call
360             // sites to be linked again, generating additional proxy classes.
361             // If the caller or a superclass has been redefined, allow newly generated
362             // proxies to unload independently of the defining class loader.
363             int flags = NESTMATE_CLASS;
364             if (!JLA.hasBeenRedefined(caller.lookupClass())) {
365                 flags |= STRONG_LOADER_LINK;
366             }
367             var classdata = useImplMethodHandle? implementation : null;
368             return caller.makeHiddenClassDefiner(lambdaClassName, classBytes, lambdaProxyClassFileDumper, flags)
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                         int parameterCount = factoryType.parameterCount();
409                         for (int i = 0; i < parameterCount; i++) {
410                             cob.aload(0)
411                                .loadLocal(TypeKind.from(factoryType.parameterType(i)), cob.parameterSlot(i))
412                                .putfield(pool.fieldRefEntry(lambdaClassEntry, pool.nameAndTypeEntry(argName(i), argDescs[i])));
413                         }
414                         cob.aload(0)
415                            .invokespecial(CD_Object, INIT_NAME, MTD_void)
416                            .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), List.of()),
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 }