1 /*
  2  * Copyright (c) 2012, 2021, 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.misc.CDS;
 29 import jdk.internal.misc.VM;
 30 import jdk.internal.org.objectweb.asm.*;
 31 import sun.invoke.util.BytecodeDescriptor;
 32 import sun.invoke.util.VerifyAccess;
 33 import sun.security.action.GetPropertyAction;
 34 import sun.security.action.GetBooleanAction;
 35 
 36 import java.io.FilePermission;
 37 import java.io.Serializable;
 38 import java.lang.constant.ConstantDescs;
 39 import java.lang.invoke.MethodHandles.Lookup;
 40 import java.lang.reflect.Constructor;
 41 import java.lang.reflect.Modifier;
 42 import java.security.AccessController;
 43 import java.security.PrivilegedAction;
 44 import java.util.LinkedHashSet;
 45 import java.util.concurrent.atomic.AtomicInteger;
 46 import java.util.PropertyPermission;
 47 import java.util.Set;
 48 
 49 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.NESTMATE;
 50 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.STRONG;
 51 import static jdk.internal.org.objectweb.asm.Opcodes.*;
 52 
 53 /**
 54  * Lambda metafactory implementation which dynamically creates an
 55  * inner-class-like class per lambda callsite.
 56  *
 57  * @see LambdaMetafactory
 58  */
 59 /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory {
 60     private static final int CLASSFILE_VERSION = VM.classFileVersion();
 61     private static final String METHOD_DESCRIPTOR_VOID = Type.getMethodDescriptor(Type.VOID_TYPE);
 62     private static final String JAVA_LANG_OBJECT = "java/lang/Object";
 63     private static final String NAME_CTOR = "<init>";
 64     private static final String LAMBDA_INSTANCE_FIELD = "LAMBDA_INSTANCE$";
 65 
 66     //Serialization support
 67     private static final String NAME_SERIALIZED_LAMBDA = "java/lang/invoke/SerializedLambda";
 68     private static final String NAME_NOT_SERIALIZABLE_EXCEPTION = "java/io/NotSerializableException";
 69     private static final String DESCR_METHOD_WRITE_REPLACE = "()Ljava/lang/Object;";
 70     private static final String DESCR_METHOD_WRITE_OBJECT = "(Ljava/io/ObjectOutputStream;)V";
 71     private static final String DESCR_METHOD_READ_OBJECT = "(Ljava/io/ObjectInputStream;)V";
 72 
 73     private static final String NAME_METHOD_WRITE_REPLACE = "writeReplace";
 74     private static final String NAME_METHOD_READ_OBJECT = "readObject";
 75     private static final String NAME_METHOD_WRITE_OBJECT = "writeObject";
 76 
 77     private static final String DESCR_CLASS = "Ljava/lang/Class;";
 78     private static final String DESCR_STRING = "Ljava/lang/String;";
 79     private static final String DESCR_OBJECT = "Ljava/lang/Object;";
 80     private static final String DESCR_CTOR_SERIALIZED_LAMBDA
 81             = "(" + DESCR_CLASS + DESCR_STRING + DESCR_STRING + DESCR_STRING + "I"
 82             + DESCR_STRING + DESCR_STRING + DESCR_STRING + DESCR_STRING + "[" + DESCR_OBJECT + ")V";
 83 
 84     private static final String DESCR_CTOR_NOT_SERIALIZABLE_EXCEPTION = "(Ljava/lang/String;)V";
 85     private static final String[] SER_HOSTILE_EXCEPTIONS = new String[] {NAME_NOT_SERIALIZABLE_EXCEPTION};
 86 
 87     private static final String[] EMPTY_STRING_ARRAY = new String[0];
 88 
 89     // Used to ensure that each spun class name is unique
 90     private static final AtomicInteger counter = new AtomicInteger();
 91 
 92     // For dumping generated classes to disk, for debugging purposes
 93     private static final ProxyClassesDumper dumper;
 94 
 95     private static final boolean disableEagerInitialization;
 96 
 97     // condy to load implMethod from class data
 98     private static final ConstantDynamic implMethodCondy;
 99 
100     static {
101         final String dumpProxyClassesKey = "jdk.internal.lambda.dumpProxyClasses";
102         String dumpPath = GetPropertyAction.privilegedGetProperty(dumpProxyClassesKey);
103         dumper = (null == dumpPath) ? null : ProxyClassesDumper.getInstance(dumpPath);
104 
105         final String disableEagerInitializationKey = "jdk.internal.lambda.disableEagerInitialization";
106         disableEagerInitialization = GetBooleanAction.privilegedGetProperty(disableEagerInitializationKey);
107 
108         // condy to load implMethod from class data
109         MethodType classDataMType = MethodType.methodType(Object.class, MethodHandles.Lookup.class, String.class, Class.class);
110         Handle classDataBsm = new Handle(H_INVOKESTATIC, Type.getInternalName(MethodHandles.class), "classData",
111                                          classDataMType.descriptorString(), false);
112         implMethodCondy = new ConstantDynamic(ConstantDescs.DEFAULT_NAME, MethodHandle.class.descriptorString(), classDataBsm);
113     }
114 
115     // See context values in AbstractValidatingLambdaMetafactory
116     private final String implMethodClassName;        // Name of type containing implementation "CC"
117     private final String implMethodName;             // Name of implementation method "impl"
118     private final String implMethodDesc;             // Type descriptor for implementation methods "(I)Ljava/lang/String;"
119     private final MethodType constructorType;        // Generated class constructor type "(CC)void"
120     private final ClassWriter cw;                    // ASM class writer
121     private final String[] argNames;                 // Generated names for the constructor arguments
122     private final String[] argDescs;                 // Type descriptors for the constructor arguments
123     private final String lambdaClassName;            // Generated name for the generated class "X$$Lambda$1"
124     private final boolean useImplMethodHandle;       // use MethodHandle invocation instead of symbolic bytecode invocation
125 
126     /**
127      * General meta-factory constructor, supporting both standard cases and
128      * allowing for uncommon options such as serialization or bridging.
129      *
130      * @param caller Stacked automatically by VM; represents a lookup context
131      *               with the accessibility privileges of the caller.
132      * @param factoryType Stacked automatically by VM; the signature of the
133      *                    invoked method, which includes the expected static
134      *                    type of the returned lambda object, and the static
135      *                    types of the captured arguments for the lambda.  In
136      *                    the event that the implementation method is an
137      *                    instance method, the first argument in the invocation
138      *                    signature will correspond to the receiver.
139      * @param interfaceMethodName Name of the method in the functional interface to
140      *                   which the lambda or method reference is being
141      *                   converted, represented as a String.
142      * @param interfaceMethodType Type of the method in the functional interface to
143      *                            which the lambda or method reference is being
144      *                            converted, represented as a MethodType.
145      * @param implementation The implementation method which should be called (with
146      *                       suitable adaptation of argument types, return types,
147      *                       and adjustment for captured arguments) when methods of
148      *                       the resulting functional interface instance are invoked.
149      * @param dynamicMethodType The signature of the primary functional
150      *                          interface method after type variables are
151      *                          substituted with their instantiation from
152      *                          the capture site
153      * @param isSerializable Should the lambda be made serializable?  If set,
154      *                       either the target type or one of the additional SAM
155      *                       types must extend {@code Serializable}.
156      * @param altInterfaces Additional interfaces which the lambda object
157      *                      should implement.
158      * @param altMethods Method types for additional signatures to be
159      *                   implemented by invoking the implementation method
160      * @throws LambdaConversionException If any of the meta-factory protocol
161      *         invariants are violated
162      * @throws SecurityException If a security manager is present, and it
163      *         <a href="MethodHandles.Lookup.html#secmgr">denies access</a>
164      *         from {@code caller} to the package of {@code implementation}.
165      */
166     public InnerClassLambdaMetafactory(MethodHandles.Lookup caller,
167                                        MethodType factoryType,
168                                        String interfaceMethodName,
169                                        MethodType interfaceMethodType,
170                                        MethodHandle implementation,
171                                        MethodType dynamicMethodType,
172                                        boolean isSerializable,
173                                        Class<?>[] altInterfaces,
174                                        MethodType[] altMethods)
175             throws LambdaConversionException {
176         super(caller, factoryType, interfaceMethodName, interfaceMethodType,
177               implementation, dynamicMethodType,
178               isSerializable, altInterfaces, altMethods);
179         implMethodClassName = implClass.getName().replace('.', '/');
180         implMethodName = implInfo.getName();
181         implMethodDesc = implInfo.getMethodType().toMethodDescriptorString();
182         constructorType = factoryType.changeReturnType(Void.TYPE);
183         lambdaClassName = lambdaClassName(targetClass);
184         // If the target class invokes a protected method inherited from a
185         // superclass in a different package, or does 'invokespecial', the
186         // lambda class has no access to the resolved method. Instead, we need
187         // to pass the live implementation method handle to the proxy class
188         // to invoke directly. (javac prefers to avoid this situation by
189         // generating bridges in the target class)
190         useImplMethodHandle = (Modifier.isProtected(implInfo.getModifiers()) &&
191                                !VerifyAccess.isSamePackage(targetClass, implInfo.getDeclaringClass())) ||
192                                implKind == H_INVOKESPECIAL;
193         cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
194         int parameterCount = factoryType.parameterCount();
195         if (parameterCount > 0) {
196             argNames = new String[parameterCount];
197             argDescs = new String[parameterCount];
198             for (int i = 0; i < parameterCount; i++) {
199                 argNames[i] = "arg$" + (i + 1);
200                 argDescs[i] = BytecodeDescriptor.unparse(factoryType.parameterType(i));
201             }
202         } else {
203             argNames = argDescs = EMPTY_STRING_ARRAY;
204         }
205     }
206 
207     private static String lambdaClassName(Class<?> targetClass) {
208         String name = targetClass.getName();
209         if (targetClass.isHidden()) {
210             // use the original class name
211             name = name.replace('/', '_');
212         }
213         return name.replace('.', '/') + "$$Lambda$" + counter.incrementAndGet();
214     }
215 
216     /**
217      * Build the CallSite. Generate a class file which implements the functional
218      * interface, define the class, if there are no parameters create an instance
219      * of the class which the CallSite will return, otherwise, generate handles
220      * which will call the class' constructor.
221      *
222      * @return a CallSite, which, when invoked, will return an instance of the
223      * functional interface
224      * @throws LambdaConversionException If properly formed functional interface
225      * is not found
226      */
227     @Override
228     CallSite buildCallSite() throws LambdaConversionException {
229         final Class<?> innerClass = spinInnerClass();
230         if (factoryType.parameterCount() == 0) {
231             // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance,
232             // unless we've suppressed eager initialization
233             if (disableEagerInitialization) {
234                 try {
235                     return new ConstantCallSite(caller.findStaticGetter(innerClass, LAMBDA_INSTANCE_FIELD,
236                             factoryType.returnType()));
237                 } catch (ReflectiveOperationException e) {
238                     throw new LambdaConversionException(
239                             "Exception finding " +  LAMBDA_INSTANCE_FIELD + " static field", e);
240                 }
241             } else {
242                 @SuppressWarnings("removal")
243                 final Constructor<?>[] ctrs = AccessController.doPrivileged(
244                         new PrivilegedAction<>() {
245                             @Override
246                             public Constructor<?>[] run() {
247                                 Constructor<?>[] ctrs = innerClass.getDeclaredConstructors();
248                                 if (ctrs.length == 1) {
249                                     // The lambda implementing inner class constructor is private, set
250                                     // it accessible (by us) before creating the constant sole instance
251                                     ctrs[0].setAccessible(true);
252                                 }
253                                 return ctrs;
254                             }
255                         });
256                 if (ctrs.length != 1) {
257                     throw new LambdaConversionException("Expected one lambda constructor for "
258                             + innerClass.getCanonicalName() + ", got " + ctrs.length);
259                 }
260 
261                 try {
262                     Object inst = ctrs[0].newInstance();
263                     return new ConstantCallSite(MethodHandles.constant(interfaceClass, inst));
264                 } catch (ReflectiveOperationException e) {
265                     throw new LambdaConversionException("Exception instantiating lambda object", e);
266                 }
267             }
268         } else {
269             try {
270                 MethodHandle mh = caller.findConstructor(innerClass, constructorType);
271                 return new ConstantCallSite(mh.asType(factoryType));
272             } catch (ReflectiveOperationException e) {
273                 throw new LambdaConversionException("Exception finding constructor", e);
274             }
275         }
276     }
277 
278     /**
279      * Spins the lambda proxy class.
280      *
281      * This first checks if a lambda proxy class can be loaded from CDS archive.
282      * Otherwise, generate the lambda proxy class. If CDS dumping is enabled, it
283      * registers the lambda proxy class for including into the CDS archive.
284      */
285     private Class<?> spinInnerClass() throws LambdaConversionException {
286         // CDS does not handle disableEagerInitialization.
287         if (!disableEagerInitialization) {
288             // include lambda proxy class in CDS archive at dump time
289             if (CDS.isDumpingArchive()) {
290                 Class<?> innerClass = generateInnerClass();
291                 LambdaProxyClassArchive.register(targetClass,
292                                                  interfaceMethodName,
293                                                  factoryType,
294                                                  interfaceMethodType,
295                                                  implementation,
296                                                  dynamicMethodType,
297                                                  isSerializable,
298                                                  altInterfaces,
299                                                  altMethods,
300                                                  innerClass);
301                 return innerClass;
302             }
303 
304             // load from CDS archive if present
305             Class<?> innerClass = LambdaProxyClassArchive.find(targetClass,
306                                                                interfaceMethodName,
307                                                                factoryType,
308                                                                interfaceMethodType,
309                                                                implementation,
310                                                                dynamicMethodType,
311                                                                isSerializable,
312                                                                altInterfaces,
313                                                                altMethods);
314             if (innerClass != null) return innerClass;
315         }
316         return generateInnerClass();
317     }
318 
319     /**
320      * Generate a class file which implements the functional
321      * interface, define and return the class.
322      *
323      * @return a Class which implements the functional interface
324      * @throws LambdaConversionException If properly formed functional interface
325      * is not found
326      */
327     @SuppressWarnings("removal")
328     private Class<?> generateInnerClass() throws LambdaConversionException {
329         String[] interfaceNames;
330         String interfaceName = interfaceClass.getName().replace('.', '/');
331         boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(interfaceClass);
332         if (altInterfaces.length == 0) {
333             interfaceNames = new String[]{interfaceName};
334         } else {
335             // Assure no duplicate interfaces (ClassFormatError)
336             Set<String> itfs = new LinkedHashSet<>(altInterfaces.length + 1);
337             itfs.add(interfaceName);
338             for (Class<?> i : altInterfaces) {
339                 itfs.add(i.getName().replace('.', '/'));
340                 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(i);
341             }
342             interfaceNames = itfs.toArray(new String[itfs.size()]);
343         }
344 
345         cw.visit(CLASSFILE_VERSION, ACC_SUPER + ACC_FINAL + ACC_SYNTHETIC,
346                  lambdaClassName, null,
347                  JAVA_LANG_OBJECT, interfaceNames);
348 
349         // Generate final fields to be filled in by constructor
350         for (int i = 0; i < argDescs.length; i++) {
351             FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_FINAL,
352                                             argNames[i],
353                                             argDescs[i],
354                                             null, null);
355             fv.visitEnd();
356         }
357 
358         generateConstructor();
359 
360         if (factoryType.parameterCount() == 0 && disableEagerInitialization) {
361             generateClassInitializer();
362         }
363 
364         // Forward the SAM method
365         MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, interfaceMethodName,
366                                           interfaceMethodType.toMethodDescriptorString(), null, null);
367         new ForwardingMethodGenerator(mv).generate(interfaceMethodType);
368 
369         // Forward the altMethods
370         if (altMethods != null) {
371             for (MethodType mt : altMethods) {
372                 mv = cw.visitMethod(ACC_PUBLIC, interfaceMethodName,
373                                     mt.toMethodDescriptorString(), null, null);
374                 new ForwardingMethodGenerator(mv).generate(mt);
375             }
376         }
377 
378         if (isSerializable)
379             generateSerializationFriendlyMethods();
380         else if (accidentallySerializable)
381             generateSerializationHostileMethods();
382 
383         cw.visitEnd();
384 
385         // Define the generated class in this VM.
386 
387         final byte[] classBytes = cw.toByteArray();
388         // If requested, dump out to a file for debugging purposes
389         if (dumper != null) {
390             AccessController.doPrivileged(new PrivilegedAction<>() {
391                 @Override
392                 public Void run() {
393                     dumper.dumpClass(lambdaClassName, classBytes);
394                     return null;
395                 }
396             }, null,
397             new FilePermission("<<ALL FILES>>", "read, write"),
398             // createDirectories may need it
399             new PropertyPermission("user.dir", "read"));
400         }
401         try {
402             // this class is linked at the indy callsite; so define a hidden nestmate
403             Lookup lookup;
404             if (useImplMethodHandle) {
405                 lookup = caller.defineHiddenClassWithClassData(classBytes, implementation, !disableEagerInitialization,
406                                                                NESTMATE, STRONG);
407             } else {
408                 lookup = caller.defineHiddenClass(classBytes, !disableEagerInitialization, NESTMATE, STRONG);
409             }
410             return lookup.lookupClass();
411         } catch (IllegalAccessException e) {
412             throw new LambdaConversionException("Exception defining lambda proxy class", e);
413         } catch (Throwable t) {
414             throw new InternalError(t);
415         }
416     }
417 
418     /**
419      * Generate a static field and a static initializer that sets this field to an instance of the lambda
420      */
421     private void generateClassInitializer() {
422         String lambdaTypeDescriptor = factoryType.returnType().descriptorString();
423 
424         // Generate the static final field that holds the lambda singleton
425         FieldVisitor fv = cw.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL,
426                 LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor, null, null);
427         fv.visitEnd();
428 
429         // Instantiate the lambda and store it to the static final field
430         MethodVisitor clinit = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
431         clinit.visitCode();
432 
433         clinit.visitTypeInsn(NEW, lambdaClassName);
434         clinit.visitInsn(Opcodes.DUP);
435         assert factoryType.parameterCount() == 0;
436         clinit.visitMethodInsn(INVOKESPECIAL, lambdaClassName, NAME_CTOR, constructorType.toMethodDescriptorString(), false);
437         clinit.visitFieldInsn(PUTSTATIC, lambdaClassName, LAMBDA_INSTANCE_FIELD, lambdaTypeDescriptor);
438 
439         clinit.visitInsn(RETURN);
440         clinit.visitMaxs(-1, -1);
441         clinit.visitEnd();
442     }
443 
444     /**
445      * Generate the constructor for the class
446      */
447     private void generateConstructor() {
448         // Generate constructor
449         MethodVisitor ctor = cw.visitMethod(ACC_PRIVATE, NAME_CTOR,
450                                             constructorType.toMethodDescriptorString(), null, null);
451         ctor.visitCode();
452         ctor.visitVarInsn(ALOAD, 0);
453         ctor.visitMethodInsn(INVOKESPECIAL, JAVA_LANG_OBJECT, NAME_CTOR,
454                              METHOD_DESCRIPTOR_VOID, false);
455         int parameterCount = factoryType.parameterCount();
456         for (int i = 0, lvIndex = 0; i < parameterCount; i++) {
457             ctor.visitVarInsn(ALOAD, 0);
458             Class<?> argType = factoryType.parameterType(i);
459             ctor.visitVarInsn(getLoadOpcode(argType), lvIndex + 1);
460             lvIndex += getParameterSize(argType);
461             ctor.visitFieldInsn(PUTFIELD, lambdaClassName, argNames[i], argDescs[i]);
462         }
463         ctor.visitInsn(RETURN);
464         // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored
465         ctor.visitMaxs(-1, -1);
466         ctor.visitEnd();
467     }
468 
469     /**
470      * Generate a writeReplace method that supports serialization
471      */
472     private void generateSerializationFriendlyMethods() {
473         TypeConvertingMethodAdapter mv
474                 = new TypeConvertingMethodAdapter(
475                     cw.visitMethod(ACC_PRIVATE + ACC_FINAL,
476                     NAME_METHOD_WRITE_REPLACE, DESCR_METHOD_WRITE_REPLACE,
477                     null, null));
478 
479         mv.visitCode();
480         mv.visitTypeInsn(NEW, NAME_SERIALIZED_LAMBDA);
481         mv.visitInsn(DUP);
482         mv.visitLdcInsn(Type.getType(targetClass));
483         mv.visitLdcInsn(factoryType.returnType().getName().replace('.', '/'));
484         mv.visitLdcInsn(interfaceMethodName);
485         mv.visitLdcInsn(interfaceMethodType.toMethodDescriptorString());
486         mv.visitLdcInsn(implInfo.getReferenceKind());
487         mv.visitLdcInsn(implInfo.getDeclaringClass().getName().replace('.', '/'));
488         mv.visitLdcInsn(implInfo.getName());
489         mv.visitLdcInsn(implInfo.getMethodType().toMethodDescriptorString());
490         mv.visitLdcInsn(dynamicMethodType.toMethodDescriptorString());
491         mv.iconst(argDescs.length);
492         mv.visitTypeInsn(ANEWARRAY, JAVA_LANG_OBJECT);
493         for (int i = 0; i < argDescs.length; i++) {
494             mv.visitInsn(DUP);
495             mv.iconst(i);
496             mv.visitVarInsn(ALOAD, 0);
497             mv.visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], argDescs[i]);
498             mv.boxIfTypePrimitive(Type.getType(argDescs[i]));
499             mv.visitInsn(AASTORE);
500         }
501         mv.visitMethodInsn(INVOKESPECIAL, NAME_SERIALIZED_LAMBDA, NAME_CTOR,
502                 DESCR_CTOR_SERIALIZED_LAMBDA, false);
503         mv.visitInsn(ARETURN);
504         // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored
505         mv.visitMaxs(-1, -1);
506         mv.visitEnd();
507     }
508 
509     /**
510      * Generate a readObject/writeObject method that is hostile to serialization
511      */
512     private void generateSerializationHostileMethods() {
513         MethodVisitor mv = cw.visitMethod(ACC_PRIVATE + ACC_FINAL,
514                                           NAME_METHOD_WRITE_OBJECT, DESCR_METHOD_WRITE_OBJECT,
515                                           null, SER_HOSTILE_EXCEPTIONS);
516         mv.visitCode();
517         mv.visitTypeInsn(NEW, NAME_NOT_SERIALIZABLE_EXCEPTION);
518         mv.visitInsn(DUP);
519         mv.visitLdcInsn("Non-serializable lambda");
520         mv.visitMethodInsn(INVOKESPECIAL, NAME_NOT_SERIALIZABLE_EXCEPTION, NAME_CTOR,
521                            DESCR_CTOR_NOT_SERIALIZABLE_EXCEPTION, false);
522         mv.visitInsn(ATHROW);
523         mv.visitMaxs(-1, -1);
524         mv.visitEnd();
525 
526         mv = cw.visitMethod(ACC_PRIVATE + ACC_FINAL,
527                             NAME_METHOD_READ_OBJECT, DESCR_METHOD_READ_OBJECT,
528                             null, SER_HOSTILE_EXCEPTIONS);
529         mv.visitCode();
530         mv.visitTypeInsn(NEW, NAME_NOT_SERIALIZABLE_EXCEPTION);
531         mv.visitInsn(DUP);
532         mv.visitLdcInsn("Non-serializable lambda");
533         mv.visitMethodInsn(INVOKESPECIAL, NAME_NOT_SERIALIZABLE_EXCEPTION, NAME_CTOR,
534                            DESCR_CTOR_NOT_SERIALIZABLE_EXCEPTION, false);
535         mv.visitInsn(ATHROW);
536         mv.visitMaxs(-1, -1);
537         mv.visitEnd();
538     }
539 
540     /**
541      * This class generates a method body which calls the lambda implementation
542      * method, converting arguments, as needed.
543      */
544     private class ForwardingMethodGenerator extends TypeConvertingMethodAdapter {
545 
546         ForwardingMethodGenerator(MethodVisitor mv) {
547             super(mv);
548         }
549 
550         void generate(MethodType methodType) {
551             visitCode();
552 
553             if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
554                 visitTypeInsn(NEW, implMethodClassName);
555                 visitInsn(DUP);
556             }
557             if (useImplMethodHandle) {
558                 visitLdcInsn(implMethodCondy);
559             }
560             for (int i = 0; i < argNames.length; i++) {
561                 visitVarInsn(ALOAD, 0);
562                 visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], argDescs[i]);
563             }
564 
565             convertArgumentTypes(methodType);
566 
567             if (useImplMethodHandle) {
568                 MethodType mtype = implInfo.getMethodType();
569                 if (implKind != MethodHandleInfo.REF_invokeStatic) {
570                     mtype = mtype.insertParameterTypes(0, implClass);
571                 }
572                 visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle",
573                                 "invokeExact", mtype.descriptorString(), false);
574             } else {
575                 // Invoke the method we want to forward to
576                 visitMethodInsn(invocationOpcode(), implMethodClassName,
577                                 implMethodName, implMethodDesc,
578                                 implClass.isInterface());
579             }
580             // Convert the return value (if any) and return it
581             // Note: if adapting from non-void to void, the 'return'
582             // instruction will pop the unneeded result
583             Class<?> implReturnClass = implMethodType.returnType();
584             Class<?> samReturnClass = methodType.returnType();
585             convertType(implReturnClass, samReturnClass, samReturnClass);
586             visitInsn(getReturnOpcode(samReturnClass));
587             // Maxs computed by ClassWriter.COMPUTE_MAXS,these arguments ignored
588             visitMaxs(-1, -1);
589             visitEnd();
590         }
591 
592         private void convertArgumentTypes(MethodType samType) {
593             int lvIndex = 0;
594             int samParametersLength = samType.parameterCount();
595             int captureArity = factoryType.parameterCount();
596             for (int i = 0; i < samParametersLength; i++) {
597                 Class<?> argType = samType.parameterType(i);
598                 visitVarInsn(getLoadOpcode(argType), lvIndex + 1);
599                 lvIndex += getParameterSize(argType);
600                 convertType(argType, implMethodType.parameterType(captureArity + i), dynamicMethodType.parameterType(i));
601             }
602         }
603 
604         private int invocationOpcode() throws InternalError {
605             return switch (implKind) {
606                 case MethodHandleInfo.REF_invokeStatic     -> INVOKESTATIC;
607                 case MethodHandleInfo.REF_newInvokeSpecial -> INVOKESPECIAL;
608                 case MethodHandleInfo.REF_invokeVirtual    -> INVOKEVIRTUAL;
609                 case MethodHandleInfo.REF_invokeInterface  -> INVOKEINTERFACE;
610                 case MethodHandleInfo.REF_invokeSpecial    -> INVOKESPECIAL;
611                 default -> throw new InternalError("Unexpected invocation kind: " + implKind);
612             };
613         }
614     }
615 
616     static int getParameterSize(Class<?> c) {
617         if (c == Void.TYPE) {
618             return 0;
619         } else if (c == Long.TYPE || c == Double.TYPE) {
620             return 2;
621         }
622         return 1;
623     }
624 
625     static int getLoadOpcode(Class<?> c) {
626         if(c == Void.TYPE) {
627             throw new InternalError("Unexpected void type of load opcode");
628         }
629         return ILOAD + getOpcodeOffset(c);
630     }
631 
632     static int getReturnOpcode(Class<?> c) {
633         if(c == Void.TYPE) {
634             return RETURN;
635         }
636         return IRETURN + getOpcodeOffset(c);
637     }
638 
639     private static int getOpcodeOffset(Class<?> c) {
640         if (c.isPrimitive()) {
641             if (c == Long.TYPE) {
642                 return 1;
643             } else if (c == Float.TYPE) {
644                 return 2;
645             } else if (c == Double.TYPE) {
646                 return 3;
647             }
648             return 0;
649         } else {
650             return 4;
651         }
652     }
653 
654 }