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      */
AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller, MethodType invokedType, String samMethodName, MethodType samMethodType, MethodHandle implMethod, MethodType instantiatedMethodType, boolean isSerializable, Class<?>[] markerInterfaces, MethodType[] additionalBridges)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.implKind = REF_invokeSpecial;
147                 this.implIsInstanceMethod = true;
148                 break;
149             case REF_invokeStatic:
150             case REF_newInvokeSpecial:
151                 // JDK-8172817: should use referenced class here for invokestatic, but we don't know what it was
152                 this.implClass = implInfo.getDeclaringClass();
153                 this.implKind = implInfo.getReferenceKind();
154                 this.implIsInstanceMethod = false;
155                 break;
156             default:
157                 throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
158         }
159 
160         this.instantiatedMethodType = instantiatedMethodType;
161         this.isSerializable = isSerializable;
162         this.markerInterfaces = markerInterfaces;
163         this.additionalBridges = additionalBridges;
164 
165         if (samMethodName.isEmpty() ||
166                 samMethodName.indexOf('.') >= 0 ||
167                 samMethodName.indexOf(';') >= 0 ||
168                 samMethodName.indexOf('[') >= 0 ||
169                 samMethodName.indexOf('/') >= 0 ||
170                 samMethodName.indexOf('<') >= 0 ||
171                 samMethodName.indexOf('>') >= 0) {
172             throw new LambdaConversionException(String.format(
173                     "Method name '%s' is not legal",
174                     samMethodName));
175         }
176 
177         if (!samBase.isInterface()) {
178             throw new LambdaConversionException(String.format(
179                     "Functional interface %s is not an interface",
180                     samBase.getName()));
181         }
182 
183         for (Class<?> c : markerInterfaces) {
184             if (!c.isInterface()) {
185                 throw new LambdaConversionException(String.format(
186                         "Marker interface %s is not an interface",
187                         c.getName()));
188             }
189         }
190     }
191 
192     /**
193      * Build the CallSite.
194      *
195      * @return a CallSite, which, when invoked, will return an instance of the
196      * functional interface
197      * @throws ReflectiveOperationException
198      */
buildCallSite()199     abstract CallSite buildCallSite()
200             throws LambdaConversionException;
201 
202     /**
203      * Check the meta-factory arguments for errors
204      * @throws LambdaConversionException if there are improper conversions
205      */
validateMetafactoryArgs()206     void validateMetafactoryArgs() throws LambdaConversionException {
207         // Check arity: captured + SAM == impl
208         final int implArity = implMethodType.parameterCount();
209         final int capturedArity = invokedType.parameterCount();
210         final int samArity = samMethodType.parameterCount();
211         final int instantiatedArity = instantiatedMethodType.parameterCount();
212         if (implArity != capturedArity + samArity) {
213             throw new LambdaConversionException(
214                     String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
215                                   implIsInstanceMethod ? "instance" : "static", implInfo,
216                                   capturedArity, samArity, implArity));
217         }
218         if (instantiatedArity != samArity) {
219             throw new LambdaConversionException(
220                     String.format("Incorrect number of parameters for %s method %s; %d instantiated parameters, %d functional interface method parameters",
221                                   implIsInstanceMethod ? "instance" : "static", implInfo,
222                                   instantiatedArity, samArity));
223         }
224         for (MethodType bridgeMT : additionalBridges) {
225             if (bridgeMT.parameterCount() != samArity) {
226                 throw new LambdaConversionException(
227                         String.format("Incorrect number of parameters for bridge signature %s; incompatible with %s",
228                                       bridgeMT, samMethodType));
229             }
230         }
231 
232         // If instance: first captured arg (receiver) must be subtype of class where impl method is defined
233         final int capturedStart; // index of first non-receiver capture parameter in implMethodType
234         final int samStart; // index of first non-receiver sam parameter in implMethodType
235         if (implIsInstanceMethod) {
236             final Class<?> receiverClass;
237 
238             // implementation is an instance method, adjust for receiver in captured variables / SAM arguments
239             if (capturedArity == 0) {
240                 // receiver is function parameter
241                 capturedStart = 0;
242                 samStart = 1;
243                 receiverClass = instantiatedMethodType.parameterType(0);
244             } else {
245                 // receiver is a captured variable
246                 capturedStart = 1;
247                 samStart = capturedArity;
248                 receiverClass = invokedType.parameterType(0);
249             }
250 
251             // check receiver type
252             if (!implClass.isAssignableFrom(receiverClass)) {
253                 throw new LambdaConversionException(
254                         String.format("Invalid receiver type %s; not a subtype of implementation type %s",
255                                       receiverClass, implClass));
256             }
257         } else {
258             // no receiver
259             capturedStart = 0;
260             samStart = capturedArity;
261         }
262 
263         // Check for exact match on non-receiver captured arguments
264         for (int i=capturedStart; i<capturedArity; i++) {
265             Class<?> implParamType = implMethodType.parameterType(i);
266             Class<?> capturedParamType = invokedType.parameterType(i);
267             if (!capturedParamType.equals(implParamType)) {
268                 throw new LambdaConversionException(
269                         String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
270                                       i, capturedParamType, implParamType));
271             }
272         }
273         // Check for adaptation match on non-receiver SAM arguments
274         for (int i=samStart; i<implArity; i++) {
275             Class<?> implParamType = implMethodType.parameterType(i);
276             Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i - capturedArity);
277             if (!isAdaptableTo(instantiatedParamType, implParamType, true)) {
278                 throw new LambdaConversionException(
279                         String.format("Type mismatch for lambda argument %d: %s is not convertible to %s",
280                                       i, instantiatedParamType, implParamType));
281             }
282         }
283 
284         // Adaptation match: return type
285         Class<?> expectedType = instantiatedMethodType.returnType();
286         Class<?> actualReturnType = implMethodType.returnType();
287         if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
288             throw new LambdaConversionException(
289                     String.format("Type mismatch for lambda return: %s is not convertible to %s",
290                                   actualReturnType, expectedType));
291         }
292 
293         // Check descriptors of generated methods
294         checkDescriptor(samMethodType);
295         for (MethodType bridgeMT : additionalBridges) {
296             checkDescriptor(bridgeMT);
297         }
298     }
299 
300     /** Validate that the given descriptor's types are compatible with {@code instantiatedMethodType} **/
checkDescriptor(MethodType descriptor)301     private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
302         for (int i = 0; i < instantiatedMethodType.parameterCount(); i++) {
303             Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i);
304             Class<?> descriptorParamType = descriptor.parameterType(i);
305             if (!descriptorParamType.isAssignableFrom(instantiatedParamType)) {
306                 String msg = String.format("Type mismatch for instantiated parameter %d: %s is not a subtype of %s",
307                                            i, instantiatedParamType, descriptorParamType);
308                 throw new LambdaConversionException(msg);
309             }
310         }
311 
312         Class<?> instantiatedReturnType = instantiatedMethodType.returnType();
313         Class<?> descriptorReturnType = descriptor.returnType();
314         if (!isAdaptableToAsReturnStrict(instantiatedReturnType, descriptorReturnType)) {
315             String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
316                                        instantiatedReturnType, descriptorReturnType);
317             throw new LambdaConversionException(msg);
318         }
319     }
320 
321     /**
322      * Check type adaptability for parameter types.
323      * @param fromType Type to convert from
324      * @param toType Type to convert to
325      * @param strict If true, do strict checks, else allow that fromType may be parameterized
326      * @return True if 'fromType' can be passed to an argument of 'toType'
327      */
isAdaptableTo(Class<?> fromType, Class<?> toType, boolean strict)328     private boolean isAdaptableTo(Class<?> fromType, Class<?> toType, boolean strict) {
329         if (fromType.equals(toType)) {
330             return true;
331         }
332         if (fromType.isPrimitive()) {
333             Wrapper wfrom = forPrimitiveType(fromType);
334             if (toType.isPrimitive()) {
335                 // both are primitive: widening
336                 Wrapper wto = forPrimitiveType(toType);
337                 return wto.isConvertibleFrom(wfrom);
338             } else {
339                 // from primitive to reference: boxing
340                 return toType.isAssignableFrom(wfrom.wrapperType());
341             }
342         } else {
343             if (toType.isPrimitive()) {
344                 // from reference to primitive: unboxing
345                 Wrapper wfrom;
346                 if (isWrapperType(fromType) && (wfrom = forWrapperType(fromType)).primitiveType().isPrimitive()) {
347                     // fromType is a primitive wrapper; unbox+widen
348                     Wrapper wto = forPrimitiveType(toType);
349                     return wto.isConvertibleFrom(wfrom);
350                 } else {
351                     // must be convertible to primitive
352                     return !strict;
353                 }
354             } else {
355                 // both are reference types: fromType should be a superclass of toType.
356                 return !strict || toType.isAssignableFrom(fromType);
357             }
358         }
359     }
360 
361     /**
362      * Check type adaptability for return types --
363      * special handling of void type) and parameterized fromType
364      * @return True if 'fromType' can be converted to 'toType'
365      */
isAdaptableToAsReturn(Class<?> fromType, Class<?> toType)366     private boolean isAdaptableToAsReturn(Class<?> fromType, Class<?> toType) {
367         return toType.equals(void.class)
368                || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false);
369     }
isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType)370     private boolean isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType) {
371         if (fromType.equals(void.class) || toType.equals(void.class)) return fromType.equals(toType);
372         else return isAdaptableTo(fromType, toType, true);
373     }
374 
375 
376     /*********** Logging support -- for debugging only, uncomment as needed
377     static final Executor logPool = Executors.newSingleThreadExecutor();
378     protected static void log(final String s) {
379         MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
380             @Override
381             public void run() {
382                 System.out.println(s);
383             }
384         });
385     }
386 
387     protected static void log(final String s, final Throwable e) {
388         MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
389             @Override
390             public void run() {
391                 System.out.println(s);
392                 e.printStackTrace(System.out);
393             }
394         });
395     }
396     ***********************/
397 
398 }
399