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