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