< 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

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

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

  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

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

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();
< prev index next >