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 package java.lang.invoke;
  26 
  27 import sun.invoke.util.Wrapper;
  28 
  29 import static java.lang.invoke.MethodHandleInfo.*;
  30 import static sun.invoke.util.Wrapper.forPrimitiveType;
  31 import static sun.invoke.util.Wrapper.forWrapperType;
  32 import static sun.invoke.util.Wrapper.isWrapperType;
  33 
  34 /**
  35  * Abstract implementation of a lambda metafactory which provides parameter
  36  * unrolling and input validation.
  37  *
  38  * @see LambdaMetafactory
  39  */
  40 /* package */ abstract class AbstractValidatingLambdaMetafactory {
  41 
  42     /*
  43      * For context, the comments for the following fields are marked in quotes
  44      * with their values, given this program:
  45      * interface II<T> {  Object foo(T x); }
  46      * interface JJ<R extends Number> extends II<R> { }
  47      * class CC {  String impl(int i) { return "impl:"+i; }}
  48      * class X {
  49      *     public static void main(String[] args) {
  50      *         JJ<Integer> iii = (new CC())::impl;
  51      *         System.out.printf(">>> %s\n", iii.foo(44));
  52      * }}
  53      */
  54     final MethodHandles.Lookup caller;        // The caller's lookup context
  55     final Class<?> targetClass;               // The class calling the meta-factory via invokedynamic "class X"
  56     final MethodType invokedType;             // The type of the invoked method "(CC)II"
  57     final Class<?> samBase;                   // The type of the returned instance "interface JJ"
  58     final String samMethodName;               // Name of the SAM method "foo"
  59     final MethodType samMethodType;           // Type of the SAM method "(Object)Object"
  60     final MethodHandle implMethod;            // Raw method handle for the implementation method
  61     final MethodType implMethodType;          // Type of the implMethod MethodHandle "(CC,int)String"
  62     final MethodHandleInfo implInfo;          // Info about the implementation method handle "MethodHandleInfo[5 CC.impl(int)String]"
  63     final int implKind;                       // Invocation kind for implementation "5"=invokevirtual
  64     final boolean implIsInstanceMethod;       // Is the implementation an instance method "true"
  65     final Class<?> implClass;                 // Class for referencing the implementation method "class CC"
  66     final MethodType instantiatedMethodType;  // Instantiated erased functional interface method type "(Integer)Object"
  67     final boolean isSerializable;             // Should the returned instance be serializable
  68     final Class<?>[] markerInterfaces;        // Additional marker interfaces to be implemented
  69     final MethodType[] additionalBridges;     // Signatures of additional methods to bridge
  70 
  71 
  72     /**
  73      * Meta-factory constructor.
  74      *
  75      * @param caller Stacked automatically by VM; represents a lookup context
  76      *               with the accessibility privileges of the caller.
  77      * @param invokedType Stacked automatically by VM; the signature of the
  78      *                    invoked method, which includes the expected static
  79      *                    type of the returned lambda object, and the static
  80      *                    types of the captured arguments for the lambda.  In
  81      *                    the event that the implementation method is an
  82      *                    instance method, the first argument in the invocation
  83      *                    signature will correspond to the receiver.
  84      * @param samMethodName Name of the method in the functional interface to
  85      *                      which the lambda or method reference is being
  86      *                      converted, represented as a String.
  87      * @param samMethodType Type of the method in the functional interface to
  88      *                      which the lambda or method reference is being
  89      *                      converted, represented as a MethodType.
  90      * @param implMethod The implementation method which should be called
  91      *                   (with suitable adaptation of argument types, return
  92      *                   types, and adjustment for captured arguments) when
  93      *                   methods of the resulting functional interface instance
  94      *                   are invoked.
  95      * @param instantiatedMethodType The signature of the primary functional
  96      *                               interface method after type variables are
  97      *                               substituted with their instantiation from
  98      *                               the capture site
  99      * @param isSerializable Should the lambda be made serializable?  If set,
 100      *                       either the target type or one of the additional SAM
 101      *                       types must extend {@code Serializable}.
 102      * @param markerInterfaces Additional interfaces which the lambda object
 103      *                       should implement.
 104      * @param additionalBridges Method types for additional signatures to be
 105      *                          bridged to the implementation method
 106      * @throws LambdaConversionException If any of the meta-factory protocol
 107      * invariants are violated
 108      */
 109     AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller,
 110                                        MethodType invokedType,
 111                                        String samMethodName,
 112                                        MethodType samMethodType,
 113                                        MethodHandle implMethod,
 114                                        MethodType instantiatedMethodType,
 115                                        boolean isSerializable,
 116                                        Class<?>[] markerInterfaces,
 117                                        MethodType[] additionalBridges)
 118             throws LambdaConversionException {
 119         if ((caller.lookupModes() & MethodHandles.Lookup.PRIVATE) == 0) {
 120             throw new LambdaConversionException(String.format(
 121                     "Invalid caller: %s",
 122                     caller.lookupClass().getName()));
 123         }
 124         this.caller = caller;
 125         this.targetClass = caller.lookupClass();
 126         this.invokedType = invokedType;
 127 
 128         this.samBase = invokedType.returnType();
 129 
 130         this.samMethodName = samMethodName;
 131         this.samMethodType  = samMethodType;
 132 
 133         this.implMethod = implMethod;
 134         this.implMethodType = implMethod.type();
 135         this.implInfo = caller.revealDirect(implMethod);
 136         switch (implInfo.getReferenceKind()) {
 137             case REF_invokeVirtual:
 138             case REF_invokeInterface:
 139                 this.implClass = implMethodType.parameterType(0);
 140                 // reference kind reported by implInfo may not match implMethodType's first param
 141                 // Example: implMethodType is (Cloneable)String, implInfo is for Object.toString
 142                 this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
 143                 this.implIsInstanceMethod = true;
 144                 break;
 145             case REF_invokeSpecial:
 146                 // JDK-8172817: should use referenced class here, but we don't know what it was
 147                 this.implClass = implInfo.getDeclaringClass();
 148                 this.implIsInstanceMethod = true;
 149 
 150                 // Classes compiled prior to dynamic nestmate support invokes a private instance
 151                 // method with REF_invokeSpecial.
 152                 //
 153                 // invokespecial should only be used to invoke private nestmate constructors.
 154                 // The lambda proxy class will be defined as a nestmate of targetClass.
 155                 // If the method to be invoked is an instance method of targetClass, then
 156                 // convert to use invokevirtual or invokeinterface.
 157                 if (targetClass == implClass && !implInfo.getName().equals("<init>")) {
 158                     this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
 159                 } else {
 160                     this.implKind = REF_invokeSpecial;
 161                 }
 162                 break;
 163             case REF_invokeStatic:
 164             case REF_newInvokeSpecial:
 165                 // JDK-8172817: should use referenced class here for invokestatic, but we don't know what it was
 166                 this.implClass = implInfo.getDeclaringClass();
 167                 this.implKind = implInfo.getReferenceKind();
 168                 this.implIsInstanceMethod = false;
 169                 break;
 170             default:
 171                 throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
 172         }
 173 
 174         this.instantiatedMethodType = instantiatedMethodType;
 175         this.isSerializable = isSerializable;
 176         this.markerInterfaces = markerInterfaces;
 177         this.additionalBridges = additionalBridges;
 178 
 179         if (samMethodName.isEmpty() ||
 180                 samMethodName.indexOf('.') >= 0 ||
 181                 samMethodName.indexOf(';') >= 0 ||
 182                 samMethodName.indexOf('[') >= 0 ||
 183                 samMethodName.indexOf('/') >= 0 ||
 184                 samMethodName.indexOf('<') >= 0 ||
 185                 samMethodName.indexOf('>') >= 0) {
 186             throw new LambdaConversionException(String.format(
 187                     "Method name '%s' is not legal",
 188                     samMethodName));
 189         }
 190 
 191         if (!samBase.isInterface()) {
 192             throw new LambdaConversionException(String.format(
 193                     "Functional interface %s is not an interface",
 194                     samBase.getName()));
 195         }
 196 
 197         for (Class<?> c : markerInterfaces) {
 198             if (!c.isInterface()) {
 199                 throw new LambdaConversionException(String.format(
 200                         "Marker interface %s is not an interface",
 201                         c.getName()));
 202             }
 203         }
 204     }
 205 
 206     /**
 207      * Build the CallSite.
 208      *
 209      * @return a CallSite, which, when invoked, will return an instance of the
 210      * functional interface
 211      * @throws ReflectiveOperationException
 212      */
 213     abstract CallSite buildCallSite()
 214             throws LambdaConversionException;
 215 
 216     /**
 217      * Check the meta-factory arguments for errors
 218      * @throws LambdaConversionException if there are improper conversions
 219      */
 220     void validateMetafactoryArgs() throws LambdaConversionException {
 221         // Check arity: captured + SAM == impl
 222         final int implArity = implMethodType.parameterCount();
 223         final int capturedArity = invokedType.parameterCount();
 224         final int samArity = samMethodType.parameterCount();
 225         final int instantiatedArity = instantiatedMethodType.parameterCount();
 226         if (implArity != capturedArity + samArity) {
 227             throw new LambdaConversionException(
 228                     String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
 229                                   implIsInstanceMethod ? "instance" : "static", implInfo,
 230                                   capturedArity, samArity, implArity));
 231         }
 232         if (instantiatedArity != samArity) {
 233             throw new LambdaConversionException(
 234                     String.format("Incorrect number of parameters for %s method %s; %d instantiated parameters, %d functional interface method parameters",
 235                                   implIsInstanceMethod ? "instance" : "static", implInfo,
 236                                   instantiatedArity, samArity));
 237         }
 238         for (MethodType bridgeMT : additionalBridges) {
 239             if (bridgeMT.parameterCount() != samArity) {
 240                 throw new LambdaConversionException(
 241                         String.format("Incorrect number of parameters for bridge signature %s; incompatible with %s",
 242                                       bridgeMT, samMethodType));
 243             }
 244         }
 245 
 246         // If instance: first captured arg (receiver) must be subtype of class where impl method is defined
 247         final int capturedStart; // index of first non-receiver capture parameter in implMethodType
 248         final int samStart; // index of first non-receiver sam parameter in implMethodType
 249         if (implIsInstanceMethod) {
 250             final Class<?> receiverClass;
 251 
 252             // implementation is an instance method, adjust for receiver in captured variables / SAM arguments
 253             if (capturedArity == 0) {
 254                 // receiver is function parameter
 255                 capturedStart = 0;
 256                 samStart = 1;
 257                 receiverClass = instantiatedMethodType.parameterType(0);
 258             } else {
 259                 // receiver is a captured variable
 260                 capturedStart = 1;
 261                 samStart = capturedArity;
 262                 receiverClass = invokedType.parameterType(0);
 263             }
 264 
 265             // check receiver type
 266             if (!implClass.isAssignableFrom(receiverClass)) {
 267                 throw new LambdaConversionException(
 268                         String.format("Invalid receiver type %s; not a subtype of implementation type %s",
 269                                       receiverClass, implClass));
 270             }
 271         } else {
 272             // no receiver
 273             capturedStart = 0;
 274             samStart = capturedArity;
 275         }
 276 
 277         // Check for exact match on non-receiver captured arguments
 278         for (int i=capturedStart; i<capturedArity; i++) {
 279             Class<?> implParamType = implMethodType.parameterType(i);
 280             Class<?> capturedParamType = invokedType.parameterType(i);
 281             if (!capturedParamType.equals(implParamType)) {
 282                 throw new LambdaConversionException(
 283                         String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
 284                                       i, capturedParamType, implParamType));
 285             }
 286         }
 287         // Check for adaptation match on non-receiver SAM arguments
 288         for (int i=samStart; i<implArity; i++) {
 289             Class<?> implParamType = implMethodType.parameterType(i);
 290             Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i - capturedArity);
 291             if (!isAdaptableTo(instantiatedParamType, implParamType, true)) {
 292                 throw new LambdaConversionException(
 293                         String.format("Type mismatch for lambda argument %d: %s is not convertible to %s",
 294                                       i, instantiatedParamType, implParamType));
 295             }
 296         }
 297 
 298         // Adaptation match: return type
 299         Class<?> expectedType = instantiatedMethodType.returnType();
 300         Class<?> actualReturnType = implMethodType.returnType();
 301         if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
 302             throw new LambdaConversionException(
 303                     String.format("Type mismatch for lambda return: %s is not convertible to %s",
 304                                   actualReturnType, expectedType));
 305         }
 306 
 307         // Check descriptors of generated methods
 308         checkDescriptor(samMethodType);
 309         for (MethodType bridgeMT : additionalBridges) {
 310             checkDescriptor(bridgeMT);
 311         }
 312     }
 313 
 314     /** Validate that the given descriptor's types are compatible with {@code instantiatedMethodType} **/
 315     private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
 316         for (int i = 0; i < instantiatedMethodType.parameterCount(); i++) {
 317             Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i);
 318             Class<?> descriptorParamType = descriptor.parameterType(i);
 319             if (!descriptorParamType.isAssignableFrom(instantiatedParamType)) {
 320                 String msg = String.format("Type mismatch for instantiated parameter %d: %s is not a subtype of %s",
 321                                            i, instantiatedParamType, descriptorParamType);
 322                 throw new LambdaConversionException(msg);
 323             }
 324         }
 325 
 326         Class<?> instantiatedReturnType = instantiatedMethodType.returnType();
 327         Class<?> descriptorReturnType = descriptor.returnType();
 328         if (!isAdaptableToAsReturnStrict(instantiatedReturnType, descriptorReturnType)) {
 329             String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
 330                                        instantiatedReturnType, descriptorReturnType);
 331             throw new LambdaConversionException(msg);
 332         }
 333     }
 334 
 335     /**
 336      * Check type adaptability for parameter types.
 337      * @param fromType Type to convert from
 338      * @param toType Type to convert to
 339      * @param strict If true, do strict checks, else allow that fromType may be parameterized
 340      * @return True if 'fromType' can be passed to an argument of 'toType'
 341      */
 342     private boolean isAdaptableTo(Class<?> fromType, Class<?> toType, boolean strict) {
 343         if (fromType.equals(toType)) {
 344             return true;
 345         }
 346         if (fromType.isPrimitive()) {
 347             Wrapper wfrom = forPrimitiveType(fromType);
 348             if (toType.isPrimitive()) {
 349                 // both are primitive: widening
 350                 Wrapper wto = forPrimitiveType(toType);
 351                 return wto.isConvertibleFrom(wfrom);
 352             } else {
 353                 // from primitive to reference: boxing
 354                 return toType.isAssignableFrom(wfrom.wrapperType());
 355             }
 356         } else {
 357             if (toType.isPrimitive()) {
 358                 // from reference to primitive: unboxing
 359                 Wrapper wfrom;
 360                 if (isWrapperType(fromType) && (wfrom = forWrapperType(fromType)).primitiveType().isPrimitive()) {
 361                     // fromType is a primitive wrapper; unbox+widen
 362                     Wrapper wto = forPrimitiveType(toType);
 363                     return wto.isConvertibleFrom(wfrom);
 364                 } else {
 365                     // must be convertible to primitive
 366                     return !strict;
 367                 }
 368             } else {
 369                 // both are reference types: fromType should be a superclass of toType.
 370                 return !strict || toType.isAssignableFrom(fromType);
 371             }
 372         }
 373     }
 374 
 375     /**
 376      * Check type adaptability for return types --
 377      * special handling of void type) and parameterized fromType
 378      * @return True if 'fromType' can be converted to 'toType'
 379      */
 380     private boolean isAdaptableToAsReturn(Class<?> fromType, Class<?> toType) {
 381         return toType.equals(void.class)
 382                || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false);
 383     }
 384     private boolean isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType) {
 385         if (fromType.equals(void.class) || toType.equals(void.class)) return fromType.equals(toType);
 386         else return isAdaptableTo(fromType, toType, true);
 387     }
 388 
 389 
 390     /*********** Logging support -- for debugging only, uncomment as needed
 391     static final Executor logPool = Executors.newSingleThreadExecutor();
 392     protected static void log(final String s) {
 393         MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
 394             @Override
 395             public void run() {
 396                 System.out.println(s);
 397             }
 398         });
 399     }
 400 
 401     protected static void log(final String s, final Throwable e) {
 402         MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
 403             @Override
 404             public void run() {
 405                 System.out.println(s);
 406                 e.printStackTrace(System.out);
 407             }
 408         });
 409     }
 410     ***********************/
 411 
 412 }