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