< prev index next >

src/java.base/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java

Print this page

  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:

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);

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

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

  1 /*
  2  * Copyright (c) 2012, 2022, 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.value.PrimitiveClass;
 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:

252         // If instance: first captured arg (receiver) must be subtype of class where impl method is defined
253         final int capturedStart; // index of first non-receiver capture parameter in implMethodType
254         final int samStart; // index of first non-receiver sam parameter in implMethodType
255         if (implIsInstanceMethod) {
256             final Class<?> receiverClass;
257 
258             // implementation is an instance method, adjust for receiver in captured variables / SAM arguments
259             if (capturedArity == 0) {
260                 // receiver is function parameter
261                 capturedStart = 0;
262                 samStart = 1;
263                 receiverClass = dynamicMethodType.parameterType(0);
264             } else {
265                 // receiver is a captured variable
266                 capturedStart = 1;
267                 samStart = capturedArity;
268                 receiverClass = factoryType.parameterType(0);
269             }
270 
271             // check receiver type
272             if (!PrimitiveClass.asPrimaryType(implClass).isAssignableFrom(PrimitiveClass.asPrimaryType(receiverClass))) {
273                 throw new LambdaConversionException(
274                         String.format("Invalid receiver type %s; not a subtype of implementation type %s",
275                                       receiverClass.descriptorString(), implClass.descriptorString()));
276             }
277         } else {
278             // no receiver
279             capturedStart = 0;
280             samStart = capturedArity;
281         }
282 
283         // Check for exact match on non-receiver captured arguments
284         for (int i=capturedStart; i<capturedArity; i++) {
285             Class<?> implParamType = implMethodType.parameterType(i);
286             Class<?> capturedParamType = factoryType.parameterType(i);
287             if (!capturedParamType.equals(implParamType)) {
288                 throw new LambdaConversionException(
289                         String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
290                                       i, capturedParamType, implParamType));
291             }
292         }
293         // Check for adaptation match on non-receiver SAM arguments
294         for (int i=samStart; i<implArity; i++) {
295             Class<?> implParamType = implMethodType.parameterType(i);

305         Class<?> expectedType = dynamicMethodType.returnType();
306         Class<?> actualReturnType = implMethodType.returnType();
307         if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
308             throw new LambdaConversionException(
309                     String.format("Type mismatch for lambda return: %s is not convertible to %s",
310                                   actualReturnType, expectedType));
311         }
312 
313         // Check descriptors of generated methods
314         checkDescriptor(interfaceMethodType);
315         for (MethodType bridgeMT : altMethods) {
316             checkDescriptor(bridgeMT);
317         }
318     }
319 
320     /** Validate that the given descriptor's types are compatible with {@code dynamicMethodType} **/
321     private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
322         for (int i = 0; i < dynamicMethodType.parameterCount(); i++) {
323             Class<?> dynamicParamType = dynamicMethodType.parameterType(i);
324             Class<?> descriptorParamType = descriptor.parameterType(i);
325             if (!PrimitiveClass.asPrimaryType(descriptorParamType).isAssignableFrom(PrimitiveClass.asPrimaryType(dynamicParamType))) {
326                 String msg = String.format("Type mismatch for dynamic parameter %d: %s is not a subtype of %s",
327                                            i, dynamicParamType, descriptorParamType);
328                 throw new LambdaConversionException(msg);
329             }
330         }
331 
332         Class<?> dynamicReturnType = dynamicMethodType.returnType();
333         Class<?> descriptorReturnType = descriptor.returnType();
334         if (!isAdaptableToAsReturnStrict(dynamicReturnType, descriptorReturnType)) {
335             String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
336                                        dynamicReturnType, descriptorReturnType);
337             throw new LambdaConversionException(msg);
338         }
339     }
340 
341     /**
342      * Check type adaptability for parameter types.
343      * @param fromType Type to convert from
344      * @param toType Type to convert to
345      * @param strict If true, do strict checks, else allow that fromType may be parameterized

355                 // both are primitive: widening
356                 Wrapper wto = forPrimitiveType(toType);
357                 return wto.isConvertibleFrom(wfrom);
358             } else {
359                 // from primitive to reference: boxing
360                 return toType.isAssignableFrom(wfrom.wrapperType());
361             }
362         } else {
363             if (toType.isPrimitive()) {
364                 // from reference to primitive: unboxing
365                 Wrapper wfrom;
366                 if (isWrapperType(fromType) && (wfrom = forWrapperType(fromType)).primitiveType().isPrimitive()) {
367                     // fromType is a primitive wrapper; unbox+widen
368                     Wrapper wto = forPrimitiveType(toType);
369                     return wto.isConvertibleFrom(wfrom);
370                 } else {
371                     // must be convertible to primitive
372                     return !strict;
373                 }
374             } else {
375                 // primitive types: fromType and toType are types of the same primitive class
376                 // identity types: fromType should be a superclass of toType.
377                 return !strict || canConvert(fromType, toType);
378             }
379         }
380     }
381 
382     /**
383      * Tests if {@code fromType} can be converted to {@code toType}
384      * via an identity conversion, via a widening reference conversion or
385      * via primitive class narrowing and widening conversions.
386      * <p>
387      * If {@code fromType} represents a class or interface, this method
388      * returns {@code true} if {@code toType} is the same as,
389      * or is a superclass or superinterface of, {@code fromType}.
390      * <p>
391      * If {@code fromType} and {@code toType} is of the same primitive class,
392      * this method returns {@code true}.
393      * <p>
394      * Otherwise, this method returns {@code false}.
395      *
396      * @param     fromType the {@code Class} object to be converted from
397      * @param     toType the {@code Class} object to be converted to
398      * @return    {@code true} if {@code fromType} can be converted to {@code toType}
399      */
400     private boolean canConvert(Class<?> fromType, Class<?> toType) {
401         if (toType.isAssignableFrom(fromType)) {
402             return true;
403         }
404 
405         if (fromType.isValue() && toType.isValue()) {
406             // val projection can be converted to ref projection; or vice verse
407             return PrimitiveClass.asPrimaryType(fromType) == PrimitiveClass.asPrimaryType(toType);
408         }
409 
410         return false;
411     }
412 
413     /**
414      * Check type adaptability for return types --
415      * special handling of void type) and parameterized fromType
416      * @return True if 'fromType' can be converted to 'toType'
417      */
418     private boolean isAdaptableToAsReturn(Class<?> fromType, Class<?> toType) {
419         return toType.equals(void.class)
420                || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false);
421     }
422     private boolean isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType) {
423         if (fromType.equals(void.class) || toType.equals(void.class)) return fromType.equals(toType);
424         else return isAdaptableTo(fromType, toType, true);
425     }
426 
427 
428     /*********** Logging support -- for debugging only, uncomment as needed
429     static final Executor logPool = Executors.newSingleThreadExecutor();
430     protected static void log(final String s) {
431         MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
432             @Override
< prev index next >