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