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.isHidden()) {
 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         if (invokedType.parameterCount() == 0 && !disableEagerInitialization) {
 211             // In the case of a non-capturing lambda, we optimize linkage by pre-computing a single instance,
 212             // unless we've suppressed eager initialization
 213             final Constructor<?>[] ctrs = AccessController.doPrivileged(
 214                     new PrivilegedAction<>() {
 215                 @Override
 216                 public Constructor<?>[] run() {
 217                     Constructor<?>[] ctrs = innerClass.getDeclaredConstructors();
 218                     if (ctrs.length == 1) {
 219                         // The lambda implementing inner class constructor is private, set
 220                         // it accessible (by us) before creating the constant sole instance
 221                         ctrs[0].setAccessible(true);
 222                     }
 223                     return ctrs;
 224                 }
 225                     });
 226             if (ctrs.length != 1) {
 227                 throw new LambdaConversionException("Expected one lambda constructor for "
 228                         + innerClass.getCanonicalName() + ", got " + ctrs.length);
 229             }
 230 
 231             try {
 232                 Object inst = ctrs[0].newInstance();
 233                 return new ConstantCallSite(MethodHandles.constant(samBase, inst));
 234             } catch (ReflectiveOperationException e) {
 235                 throw new LambdaConversionException("Exception instantiating lambda object", e);
 236             }
 237         } else {
 238             try {
 239                 MethodHandle mh = caller.findConstructor(innerClass, invokedType.changeReturnType(void.class));
 240                 return new ConstantCallSite(mh.asType(invokedType));
 241             } catch (ReflectiveOperationException e) {
 242                 throw new LambdaConversionException("Exception finding constructor", e);
 243             }
 244         }
 245     }
 246 
 247     /**
 248      * Generate a class file which implements the functional
 249      * interface, define and return the class.
 250      *
 251      * @implNote The class that is generated does not include signature
 252      * information for exceptions that may be present on the SAM method.
 253      * This is to reduce classfile size, and is harmless as checked exceptions
 254      * are erased anyway, no one will ever compile against this classfile,
 255      * and we make no guarantees about the reflective properties of lambda
 256      * objects.
 257      *
 258      * @return a Class which implements the functional interface
 259      * @throws LambdaConversionException If properly formed functional interface
 260      * is not found
 261      */
 262     private Class<?> spinInnerClass() throws LambdaConversionException {
 263         String[] interfaces;
 264         String samIntf = samBase.getName().replace('.', '/');
 265         boolean accidentallySerializable = !isSerializable && Serializable.class.isAssignableFrom(samBase);
 266         if (markerInterfaces.length == 0) {
 267             interfaces = new String[]{samIntf};
 268         } else {
 269             // Assure no duplicate interfaces (ClassFormatError)
 270             Set<String> itfs = new LinkedHashSet<>(markerInterfaces.length + 1);
 271             itfs.add(samIntf);
 272             for (Class<?> markerInterface : markerInterfaces) {
 273                 itfs.add(markerInterface.getName().replace('.', '/'));
 274                 accidentallySerializable |= !isSerializable && Serializable.class.isAssignableFrom(markerInterface);
 275             }
 276             interfaces = itfs.toArray(new String[itfs.size()]);
 277         }
 278 
 279         cw.visit(CLASSFILE_VERSION, ACC_SUPER + ACC_FINAL + ACC_SYNTHETIC,
 280                  lambdaClassName, null,
 281                  JAVA_LANG_OBJECT, interfaces);
 282 
 283         // Generate final fields to be filled in by constructor
 284         for (int i = 0; i < argDescs.length; i++) {
 285             FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_FINAL,
 286                                             argNames[i],
 287                                             argDescs[i],
 288                                             null, null);
 289             fv.visitEnd();
 290         }
 291 
 292         generateConstructor();
 293 
 294         // Forward the SAM method
 295         MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, samMethodName,
 296                                           samMethodType.toMethodDescriptorString(), null, null);
 297         new ForwardingMethodGenerator(mv).generate(samMethodType);
 298 
 299         // Forward the bridges
 300         if (additionalBridges != null) {
 301             for (MethodType mt : additionalBridges) {
 302                 mv = cw.visitMethod(ACC_PUBLIC|ACC_BRIDGE, samMethodName,
 303                                     mt.toMethodDescriptorString(), null, null);
 304                 new ForwardingMethodGenerator(mv).generate(mt);
 305             }
 306         }
 307 
 308         if (useImplMethodHandle) {
 309             FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_STATIC,
 310                                             NAME_FIELD_IMPL_METHOD,
 311                                             DESCR_METHOD_HANDLE,
 312                                             null, null);
 313             fv.visitEnd();
 314         }
 315 
 316         if (isSerializable)
 317             generateSerializationFriendlyMethods();
 318         else if (accidentallySerializable)
 319             generateSerializationHostileMethods();
 320 
 321         cw.visitEnd();
 322 
 323         // Define the generated class in this VM.
 324 
 325         final byte[] classBytes = cw.toByteArray();
 326         // If requested, dump out to a file for debugging purposes
 327         if (dumper != null) {
 328             AccessController.doPrivileged(new PrivilegedAction<>() {
 329                 @Override
 330                 public Void run() {
 331                     dumper.dumpClass(lambdaClassName, classBytes);
 332                     return null;
 333                 }
 334             }, null,
 335             new FilePermission("<<ALL FILES>>", "read, write"),
 336             // createDirectories may need it
 337             new PropertyPermission("user.dir", "read"));
 338         }
 339         try {
 340             // this class is linked at the indy callsite; so define a hidden nestmate
 341             Lookup lookup = caller.defineHiddenClass(classBytes, !disableEagerInitialization, NESTMATE, STRONG);
 342             if (useImplMethodHandle) {
 343                 // If the target class invokes a method reference this::m which is
 344                 // resolved to a protected method inherited from a superclass in a different
 345                 // package, the target class does not have a bridge and this method reference
 346                 // has been changed from public to protected after the target class was compiled.
 347                 // This lambda proxy class has no access to the resolved method.
 348                 // So this workaround by passing the live implMethod method handle
 349                 // to the proxy class to invoke directly.
 350                 MethodHandle mh = lookup.findStaticSetter(lookup.lookupClass(), NAME_FIELD_IMPL_METHOD, MethodHandle.class);
 351                 mh.invokeExact(implMethod);
 352             }
 353             return lookup.lookupClass();
 354         } catch (IllegalAccessException e) {
 355             throw new LambdaConversionException("Exception defining lambda proxy class", e);
 356         } catch (Throwable t) {
 357             throw new InternalError(t);
 358         }
 359     }
 360 
 361     /**
 362      * Generate the constructor for the class
 363      */
 364     private void generateConstructor() {
 365         // Generate constructor
 366         MethodVisitor ctor = cw.visitMethod(ACC_PRIVATE, NAME_CTOR,
 367                                             constructorType.toMethodDescriptorString(), null, null);
 368         ctor.visitCode();
 369         ctor.visitVarInsn(ALOAD, 0);
 370         ctor.visitMethodInsn(INVOKESPECIAL, JAVA_LANG_OBJECT, NAME_CTOR,
 371                              METHOD_DESCRIPTOR_VOID, false);
 372         int parameterCount = invokedType.parameterCount();
 373         for (int i = 0, lvIndex = 0; i < parameterCount; i++) {
 374             ctor.visitVarInsn(ALOAD, 0);
 375             Class<?> argType = invokedType.parameterType(i);
 376             ctor.visitVarInsn(getLoadOpcode(argType), lvIndex + 1);
 377             lvIndex += getParameterSize(argType);
 378             ctor.visitFieldInsn(PUTFIELD, lambdaClassName, argNames[i], argDescs[i]);
 379         }
 380         ctor.visitInsn(RETURN);
 381         // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored
 382         ctor.visitMaxs(-1, -1);
 383         ctor.visitEnd();
 384     }
 385 
 386     /**
 387      * Generate a writeReplace method that supports serialization
 388      */
 389     private void generateSerializationFriendlyMethods() {
 390         TypeConvertingMethodAdapter mv
 391                 = new TypeConvertingMethodAdapter(
 392                     cw.visitMethod(ACC_PRIVATE + ACC_FINAL,
 393                     NAME_METHOD_WRITE_REPLACE, DESCR_METHOD_WRITE_REPLACE,
 394                     null, null));
 395 
 396         mv.visitCode();
 397         mv.visitTypeInsn(NEW, NAME_SERIALIZED_LAMBDA);
 398         mv.visitInsn(DUP);
 399         mv.visitLdcInsn(Type.getType(targetClass));
 400         mv.visitLdcInsn(invokedType.returnType().getName().replace('.', '/'));
 401         mv.visitLdcInsn(samMethodName);
 402         mv.visitLdcInsn(samMethodType.toMethodDescriptorString());
 403         mv.visitLdcInsn(implInfo.getReferenceKind());
 404         mv.visitLdcInsn(implInfo.getDeclaringClass().getName().replace('.', '/'));
 405         mv.visitLdcInsn(implInfo.getName());
 406         mv.visitLdcInsn(implInfo.getMethodType().toMethodDescriptorString());
 407         mv.visitLdcInsn(instantiatedMethodType.toMethodDescriptorString());
 408         mv.iconst(argDescs.length);
 409         mv.visitTypeInsn(ANEWARRAY, JAVA_LANG_OBJECT);
 410         for (int i = 0; i < argDescs.length; i++) {
 411             mv.visitInsn(DUP);
 412             mv.iconst(i);
 413             mv.visitVarInsn(ALOAD, 0);
 414             mv.visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], argDescs[i]);
 415             mv.boxIfTypePrimitive(Type.getType(argDescs[i]));
 416             mv.visitInsn(AASTORE);
 417         }
 418         mv.visitMethodInsn(INVOKESPECIAL, NAME_SERIALIZED_LAMBDA, NAME_CTOR,
 419                 DESCR_CTOR_SERIALIZED_LAMBDA, false);
 420         mv.visitInsn(ARETURN);
 421         // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored
 422         mv.visitMaxs(-1, -1);
 423         mv.visitEnd();
 424     }
 425 
 426     /**
 427      * Generate a readObject/writeObject method that is hostile to serialization
 428      */
 429     private void generateSerializationHostileMethods() {
 430         MethodVisitor mv = cw.visitMethod(ACC_PRIVATE + ACC_FINAL,
 431                                           NAME_METHOD_WRITE_OBJECT, DESCR_METHOD_WRITE_OBJECT,
 432                                           null, SER_HOSTILE_EXCEPTIONS);
 433         mv.visitCode();
 434         mv.visitTypeInsn(NEW, NAME_NOT_SERIALIZABLE_EXCEPTION);
 435         mv.visitInsn(DUP);
 436         mv.visitLdcInsn("Non-serializable lambda");
 437         mv.visitMethodInsn(INVOKESPECIAL, NAME_NOT_SERIALIZABLE_EXCEPTION, NAME_CTOR,
 438                            DESCR_CTOR_NOT_SERIALIZABLE_EXCEPTION, false);
 439         mv.visitInsn(ATHROW);
 440         mv.visitMaxs(-1, -1);
 441         mv.visitEnd();
 442 
 443         mv = cw.visitMethod(ACC_PRIVATE + ACC_FINAL,
 444                             NAME_METHOD_READ_OBJECT, DESCR_METHOD_READ_OBJECT,
 445                             null, SER_HOSTILE_EXCEPTIONS);
 446         mv.visitCode();
 447         mv.visitTypeInsn(NEW, NAME_NOT_SERIALIZABLE_EXCEPTION);
 448         mv.visitInsn(DUP);
 449         mv.visitLdcInsn("Non-serializable lambda");
 450         mv.visitMethodInsn(INVOKESPECIAL, NAME_NOT_SERIALIZABLE_EXCEPTION, NAME_CTOR,
 451                            DESCR_CTOR_NOT_SERIALIZABLE_EXCEPTION, false);
 452         mv.visitInsn(ATHROW);
 453         mv.visitMaxs(-1, -1);
 454         mv.visitEnd();
 455     }
 456 
 457     /**
 458      * This class generates a method body which calls the lambda implementation
 459      * method, converting arguments, as needed.
 460      */
 461     private class ForwardingMethodGenerator extends TypeConvertingMethodAdapter {
 462 
 463         ForwardingMethodGenerator(MethodVisitor mv) {
 464             super(mv);
 465         }
 466 
 467         void generate(MethodType methodType) {
 468             visitCode();
 469 
 470             if (implKind == MethodHandleInfo.REF_newInvokeSpecial) {
 471                 visitTypeInsn(NEW, implMethodClassName);
 472                 visitInsn(DUP);
 473             }
 474             if (useImplMethodHandle) {
 475                 visitVarInsn(ALOAD, 0);
 476                 visitFieldInsn(GETSTATIC, lambdaClassName, NAME_FIELD_IMPL_METHOD, DESCR_METHOD_HANDLE);
 477             }
 478             for (int i = 0; i < argNames.length; i++) {
 479                 visitVarInsn(ALOAD, 0);
 480                 visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], argDescs[i]);
 481             }
 482 
 483             convertArgumentTypes(methodType);
 484 
 485             if (useImplMethodHandle) {
 486                 MethodType mtype = implInfo.getMethodType().insertParameterTypes(0, implClass);
 487                 visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle",
 488                                 "invokeExact", mtype.descriptorString(), false);
 489             } else {
 490                 // Invoke the method we want to forward to
 491                 visitMethodInsn(invocationOpcode(), implMethodClassName,
 492                                 implMethodName, implMethodDesc,
 493                                 implClass.isInterface());
 494             }
 495             // Convert the return value (if any) and return it
 496             // Note: if adapting from non-void to void, the 'return'
 497             // instruction will pop the unneeded result
 498             Class<?> implReturnClass = implMethodType.returnType();
 499             Class<?> samReturnClass = methodType.returnType();
 500             convertType(implReturnClass, samReturnClass, samReturnClass);
 501             visitInsn(getReturnOpcode(samReturnClass));
 502             // Maxs computed by ClassWriter.COMPUTE_MAXS,these arguments ignored
 503             visitMaxs(-1, -1);
 504             visitEnd();
 505         }
 506 
 507         private void convertArgumentTypes(MethodType samType) {
 508             int lvIndex = 0;
 509             int samParametersLength = samType.parameterCount();
 510             int captureArity = invokedType.parameterCount();
 511             for (int i = 0; i < samParametersLength; i++) {
 512                 Class<?> argType = samType.parameterType(i);
 513                 visitVarInsn(getLoadOpcode(argType), lvIndex + 1);
 514                 lvIndex += getParameterSize(argType);
 515                 convertType(argType, implMethodType.parameterType(captureArity + i), instantiatedMethodType.parameterType(i));
 516             }
 517         }
 518 
 519         private int invocationOpcode() throws InternalError {
 520             switch (implKind) {
 521                 case MethodHandleInfo.REF_invokeStatic:
 522                     return INVOKESTATIC;
 523                 case MethodHandleInfo.REF_newInvokeSpecial:
 524                     return INVOKESPECIAL;
 525                  case MethodHandleInfo.REF_invokeVirtual:
 526                     return INVOKEVIRTUAL;
 527                 case MethodHandleInfo.REF_invokeInterface:
 528                     return INVOKEINTERFACE;
 529                 case MethodHandleInfo.REF_invokeSpecial:
 530                     return INVOKESPECIAL;
 531                 default:
 532                     throw new InternalError("Unexpected invocation kind: " + implKind);
 533             }
 534         }
 535     }
 536 
 537     static int getParameterSize(Class<?> c) {
 538         if (c == Void.TYPE) {
 539             return 0;
 540         } else if (c == Long.TYPE || c == Double.TYPE) {
 541             return 2;
 542         }
 543         return 1;
 544     }
 545 
 546     static int getLoadOpcode(Class<?> c) {
 547         if(c == Void.TYPE) {
 548             throw new InternalError("Unexpected void type of load opcode");
 549         }
 550         return ILOAD + getOpcodeOffset(c);
 551     }
 552 
 553     static int getReturnOpcode(Class<?> c) {
 554         if(c == Void.TYPE) {
 555             return RETURN;
 556         }
 557         return IRETURN + getOpcodeOffset(c);
 558     }
 559 
 560     private static int getOpcodeOffset(Class<?> c) {
 561         if (c.isPrimitive()) {
 562             if (c == Long.TYPE) {
 563                 return 1;
 564             } else if (c == Float.TYPE) {
 565                 return 2;
 566             } else if (c == Double.TYPE) {
 567                 return 3;
 568             }
 569             return 0;
 570         } else {
 571             return 4;
 572         }
 573     }
 574 
 575 }