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