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