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