1 /*
  2  * Copyright (c) 2012, 2021, 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 factoryType;             // The type of the invoked method "(CC)II"
 57     final Class<?> interfaceClass;            // The type of the returned instance "interface JJ"
 58     final String interfaceMethodName;         // Name of the method to implement "foo"
 59     final MethodType interfaceMethodType;     // Type of the method to implement "(Object)Object"
 60     final MethodHandle implementation;        // Raw method handle for the implementation method
 61     final MethodType implMethodType;          // Type of the implementation 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 dynamicMethodType;       // Dynamically checked method type "(Integer)Object"
 67     final boolean isSerializable;             // Should the returned instance be serializable
 68     final Class<?>[] altInterfaces;           // Additional interfaces to be implemented
 69     final MethodType[] altMethods;            // 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 factoryType 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 interfaceMethodName 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 interfaceMethodType 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 implementation 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 dynamicMethodType 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 altInterfaces Additional interfaces which the lambda object
103      *                      should implement.
104      * @param altMethods Method types for additional signatures to be
105      *                   implemented by invoking the implementation method
106      * @throws LambdaConversionException If any of the meta-factory protocol
107      *         invariants are violated
108      * @throws SecurityException If a security manager is present, and it
109      *         <a href="MethodHandles.Lookup.html#secmgr">denies access</a>
110      *         from {@code caller} to the package of {@code implementation}.
111      */
112     AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller,
113                                         MethodType factoryType,
114                                         String interfaceMethodName,
115                                         MethodType interfaceMethodType,
116                                         MethodHandle implementation,
117                                         MethodType dynamicMethodType,
118                                         boolean isSerializable,
119                                         Class<?>[] altInterfaces,
120                                         MethodType[] altMethods)
121             throws LambdaConversionException {
122         if (!caller.hasFullPrivilegeAccess()) {
123             throw new LambdaConversionException(String.format(
124                     "Invalid caller: %s",
125                     caller.lookupClass().getName()));
126         }
127         this.caller = caller;
128         this.targetClass = caller.lookupClass();
129         this.factoryType = factoryType;
130 
131         this.interfaceClass = factoryType.returnType();
132 
133         this.interfaceMethodName = interfaceMethodName;
134         this.interfaceMethodType  = interfaceMethodType;
135 
136         this.implementation = implementation;
137         this.implMethodType = implementation.type();
138         try {
139             this.implInfo = caller.revealDirect(implementation); // may throw SecurityException
140         } catch (IllegalArgumentException e) {
141             throw new LambdaConversionException(implementation + " is not direct or cannot be cracked");
142         }
143         switch (implInfo.getReferenceKind()) {
144             case REF_invokeVirtual:
145             case REF_invokeInterface:
146                 this.implClass = implMethodType.parameterType(0);
147                 // reference kind reported by implInfo may not match implMethodType's first param
148                 // Example: implMethodType is (Cloneable)String, implInfo is for Object.toString
149                 this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
150                 this.implIsInstanceMethod = true;
151                 break;
152             case REF_invokeSpecial:
153                 // JDK-8172817: should use referenced class here, but we don't know what it was
154                 this.implClass = implInfo.getDeclaringClass();
155                 this.implIsInstanceMethod = true;
156 
157                 // Classes compiled prior to dynamic nestmate support invoke a private instance
158                 // method with REF_invokeSpecial. Newer classes use REF_invokeVirtual or
159                 // REF_invokeInterface, and we can use that instruction in the lambda class.
160                 if (targetClass == implClass) {
161                     this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
162                 } else {
163                     this.implKind = REF_invokeSpecial;
164                 }
165                 break;
166             case REF_invokeStatic:
167             case REF_newInvokeSpecial:
168                 // JDK-8172817: should use referenced class here for invokestatic, but we don't know what it was
169                 this.implClass = implInfo.getDeclaringClass();
170                 this.implKind = implInfo.getReferenceKind();
171                 this.implIsInstanceMethod = false;
172                 break;
173             default:
174                 throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
175         }
176 
177         this.dynamicMethodType = dynamicMethodType;
178         this.isSerializable = isSerializable;
179         this.altInterfaces = altInterfaces;
180         this.altMethods = altMethods;
181 
182         if (interfaceMethodName.isEmpty() ||
183                 interfaceMethodName.indexOf('.') >= 0 ||
184                 interfaceMethodName.indexOf(';') >= 0 ||
185                 interfaceMethodName.indexOf('[') >= 0 ||
186                 interfaceMethodName.indexOf('/') >= 0 ||
187                 interfaceMethodName.indexOf('<') >= 0 ||
188                 interfaceMethodName.indexOf('>') >= 0) {
189             throw new LambdaConversionException(String.format(
190                     "Method name '%s' is not legal",
191                     interfaceMethodName));
192         }
193 
194         if (!interfaceClass.isInterface()) {
195             throw new LambdaConversionException(String.format(
196                     "%s is not an interface",
197                     interfaceClass.getName()));
198         }
199 
200         for (Class<?> c : altInterfaces) {
201             if (!c.isInterface()) {
202                 throw new LambdaConversionException(String.format(
203                         "%s is not an interface",
204                         c.getName()));
205             }
206         }
207     }
208 
209     /**
210      * Build the CallSite.
211      *
212      * @return a CallSite, which, when invoked, will return an instance of the
213      * functional interface
214      * @throws LambdaConversionException
215      */
216     abstract CallSite buildCallSite()
217             throws LambdaConversionException;
218 
219     /**
220      * Check the meta-factory arguments for errors
221      * @throws LambdaConversionException if there are improper conversions
222      */
223     void validateMetafactoryArgs() throws LambdaConversionException {
224         // Check arity: captured + SAM == impl
225         final int implArity = implMethodType.parameterCount();
226         final int capturedArity = factoryType.parameterCount();
227         final int samArity = interfaceMethodType.parameterCount();
228         final int dynamicArity = dynamicMethodType.parameterCount();
229         if (implArity != capturedArity + samArity) {
230             throw new LambdaConversionException(
231                     String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
232                                   implIsInstanceMethod ? "instance" : "static", implInfo,
233                                   capturedArity, samArity, implArity));
234         }
235         if (dynamicArity != samArity) {
236             throw new LambdaConversionException(
237                     String.format("Incorrect number of parameters for %s method %s; %d dynamic parameters, %d functional interface method parameters",
238                                   implIsInstanceMethod ? "instance" : "static", implInfo,
239                                   dynamicArity, samArity));
240         }
241         for (MethodType bridgeMT : altMethods) {
242             if (bridgeMT.parameterCount() != samArity) {
243                 throw new LambdaConversionException(
244                         String.format("Incorrect number of parameters for bridge signature %s; incompatible with %s",
245                                       bridgeMT, interfaceMethodType));
246             }
247         }
248 
249         // If instance: first captured arg (receiver) must be subtype of class where impl method is defined
250         final int capturedStart; // index of first non-receiver capture parameter in implMethodType
251         final int samStart; // index of first non-receiver sam parameter in implMethodType
252         if (implIsInstanceMethod) {
253             final Class<?> receiverClass;
254 
255             // implementation is an instance method, adjust for receiver in captured variables / SAM arguments
256             if (capturedArity == 0) {
257                 // receiver is function parameter
258                 capturedStart = 0;
259                 samStart = 1;
260                 receiverClass = dynamicMethodType.parameterType(0);
261             } else {
262                 // receiver is a captured variable
263                 capturedStart = 1;
264                 samStart = capturedArity;
265                 receiverClass = factoryType.parameterType(0);
266             }
267 
268             // check receiver type
269             if (!implClass.isAssignableFrom(receiverClass)) {
270                 throw new LambdaConversionException(
271                         String.format("Invalid receiver type %s; not a subtype of implementation type %s",
272                                       receiverClass, implClass));
273             }
274         } else {
275             // no receiver
276             capturedStart = 0;
277             samStart = capturedArity;
278         }
279 
280         // Check for exact match on non-receiver captured arguments
281         for (int i=capturedStart; i<capturedArity; i++) {
282             Class<?> implParamType = implMethodType.parameterType(i);
283             Class<?> capturedParamType = factoryType.parameterType(i);
284             if (!capturedParamType.equals(implParamType)) {
285                 throw new LambdaConversionException(
286                         String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
287                                       i, capturedParamType, implParamType));
288             }
289         }
290         // Check for adaptation match on non-receiver SAM arguments
291         for (int i=samStart; i<implArity; i++) {
292             Class<?> implParamType = implMethodType.parameterType(i);
293             Class<?> dynamicParamType = dynamicMethodType.parameterType(i - capturedArity);
294             if (!isAdaptableTo(dynamicParamType, implParamType, true)) {
295                 throw new LambdaConversionException(
296                         String.format("Type mismatch for lambda argument %d: %s is not convertible to %s",
297                                       i, dynamicParamType, implParamType));
298             }
299         }
300 
301         // Adaptation match: return type
302         Class<?> expectedType = dynamicMethodType.returnType();
303         Class<?> actualReturnType = implMethodType.returnType();
304         if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
305             throw new LambdaConversionException(
306                     String.format("Type mismatch for lambda return: %s is not convertible to %s",
307                                   actualReturnType, expectedType));
308         }
309 
310         // Check descriptors of generated methods
311         checkDescriptor(interfaceMethodType);
312         for (MethodType bridgeMT : altMethods) {
313             checkDescriptor(bridgeMT);
314         }
315     }
316 
317     /** Validate that the given descriptor's types are compatible with {@code dynamicMethodType} **/
318     private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
319         for (int i = 0; i < dynamicMethodType.parameterCount(); i++) {
320             Class<?> dynamicParamType = dynamicMethodType.parameterType(i);
321             Class<?> descriptorParamType = descriptor.parameterType(i);
322             if (!descriptorParamType.isAssignableFrom(dynamicParamType)) {
323                 String msg = String.format("Type mismatch for dynamic parameter %d: %s is not a subtype of %s",
324                                            i, dynamicParamType, descriptorParamType);
325                 throw new LambdaConversionException(msg);
326             }
327         }
328 
329         Class<?> dynamicReturnType = dynamicMethodType.returnType();
330         Class<?> descriptorReturnType = descriptor.returnType();
331         if (!isAdaptableToAsReturnStrict(dynamicReturnType, descriptorReturnType)) {
332             String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
333                                        dynamicReturnType, descriptorReturnType);
334             throw new LambdaConversionException(msg);
335         }
336     }
337 
338     /**
339      * Check type adaptability for parameter types.
340      * @param fromType Type to convert from
341      * @param toType Type to convert to
342      * @param strict If true, do strict checks, else allow that fromType may be parameterized
343      * @return True if 'fromType' can be passed to an argument of 'toType'
344      */
345     private boolean isAdaptableTo(Class<?> fromType, Class<?> toType, boolean strict) {
346         if (fromType.equals(toType)) {
347             return true;
348         }
349         if (fromType.isPrimitive()) {
350             Wrapper wfrom = forPrimitiveType(fromType);
351             if (toType.isPrimitive()) {
352                 // both are primitive: widening
353                 Wrapper wto = forPrimitiveType(toType);
354                 return wto.isConvertibleFrom(wfrom);
355             } else {
356                 // from primitive to reference: boxing
357                 return toType.isAssignableFrom(wfrom.wrapperType());
358             }
359         } else {
360             if (toType.isPrimitive()) {
361                 // from reference to primitive: unboxing
362                 Wrapper wfrom;
363                 if (isWrapperType(fromType) && (wfrom = forWrapperType(fromType)).primitiveType().isPrimitive()) {
364                     // fromType is a primitive wrapper; unbox+widen
365                     Wrapper wto = forPrimitiveType(toType);
366                     return wto.isConvertibleFrom(wfrom);
367                 } else {
368                     // must be convertible to primitive
369                     return !strict;
370                 }
371             } else {
372                 // primitive types: fromType and toType are types of the same primitive class
373                 // identity types: fromType should be a superclass of toType.
374                 return !strict || canConvert(fromType, toType);
375             }
376         }
377     }
378 
379     /**
380      * Tests if {@code fromType} can be converted to {@code toType}
381      * via an identity conversion, via a widening reference conversion or
382      * via primitive class narrowing and widening conversions.
383      * <p>
384      * If {@code fromType} represents a class or interface, this method
385      * returns {@code true} if {@code toType} is the same as,
386      * or is a superclass or superinterface of, {@code fromType}.
387      * <p>
388      * If {@code fromType} and {@code toType} is of the same primitive class,
389      * this method returns {@code true}.
390      * <p>
391      * Otherwise, this method returns {@code false}.
392      *
393      * @param     fromType the {@code Class} object to be converted from
394      * @param     toType the {@code Class} object to be converted to
395      * @return    {@code true} if {@code fromType} can be converted to {@code toType}
396      */
397     private boolean canConvert(Class<?> fromType, Class<?> toType) {
398         if (toType.isAssignableFrom(fromType)) {
399             return true;
400         }
401 
402         if (fromType.isPrimitiveClass() && toType.isPrimitiveClass()) {
403             // val projection can be converted to ref projection; or vice verse
404             return fromType.asPrimaryType() == toType.asPrimaryType();
405         }
406 
407         return false;
408     }
409 
410     /**
411      * Check type adaptability for return types --
412      * special handling of void type) and parameterized fromType
413      * @return True if 'fromType' can be converted to 'toType'
414      */
415     private boolean isAdaptableToAsReturn(Class<?> fromType, Class<?> toType) {
416         return toType.equals(void.class)
417                || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false);
418     }
419     private boolean isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType) {
420         if (fromType.equals(void.class) || toType.equals(void.class)) return fromType.equals(toType);
421         else return isAdaptableTo(fromType, toType, true);
422     }
423 
424 
425     /*********** Logging support -- for debugging only, uncomment as needed
426     static final Executor logPool = Executors.newSingleThreadExecutor();
427     protected static void log(final String s) {
428         MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
429             @Override
430             public void run() {
431                 System.out.println(s);
432             }
433         });
434     }
435 
436     protected static void log(final String s, final Throwable e) {
437         MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
438             @Override
439             public void run() {
440                 System.out.println(s);
441                 e.printStackTrace(System.out);
442             }
443         });
444     }
445     ***********************/
446 
447 }