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