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();
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 }
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 }
|
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 quotableOpField; // A getter method handle that is used to retrieve the
73 // string representation of the quotable lambda's associated
74 // intermediate representation (can be null).
75 final MethodHandleInfo quotableOpFieldInfo; // Info about the quotable getter method handle (can be null).
76
77 final MethodType quotableOpType; // The type of the quotable lambda's associated
78 // intermediate representation (can be null).
79
80
81 /**
82 * Meta-factory constructor.
83 *
84 * @param caller Stacked automatically by VM; represents a lookup context
85 * with the accessibility privileges of the caller.
86 * @param factoryType Stacked automatically by VM; the signature of the
87 * invoked method, which includes the expected static
88 * type of the returned lambda object, and the static
89 * types of the captured arguments for the lambda. In
90 * the event that the implementation method is an
91 * instance method, the first argument in the invocation
92 * signature will correspond to the receiver.
93 * @param interfaceMethodName Name of the method in the functional interface to
94 * which the lambda or method reference is being
95 * converted, represented as a String.
96 * @param interfaceMethodType Type of the method in the functional interface to
97 * which the lambda or method reference is being
98 * converted, represented as a MethodType.
99 * @param implementation The implementation method which should be called
100 * (with suitable adaptation of argument types, return
101 * types, and adjustment for captured arguments) when
102 * methods of the resulting functional interface instance
103 * are invoked.
104 * @param dynamicMethodType The signature of the primary functional
105 * interface method after type variables are
106 * substituted with their instantiation from
107 * the capture site
108 * @param isSerializable Should the lambda be made serializable? If set,
109 * either the target type or one of the additional SAM
110 * types must extend {@code Serializable}.
111 * @param altInterfaces Additional interfaces which the lambda object
112 * should implement.
113 * @param altMethods Method types for additional signatures to be
114 * implemented by invoking the implementation method
115 * @param reflectiveField a {@linkplain MethodHandles.Lookup#findGetter(Class, String, Class) getter}
116 * method handle that is used to retrieve the string representation of the
117 * quotable lambda's associated intermediate representation.
118 * @throws LambdaConversionException If any of the meta-factory protocol
119 * invariants are violated
120 * @throws SecurityException If a security manager is present, and it
121 * <a href="MethodHandles.Lookup.html#secmgr">denies access</a>
122 * from {@code caller} to the package of {@code implementation}.
123 */
124 AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller,
125 MethodType factoryType,
126 String interfaceMethodName,
127 MethodType interfaceMethodType,
128 MethodHandle implementation,
129 MethodType dynamicMethodType,
130 boolean isSerializable,
131 Class<?>[] altInterfaces,
132 MethodType[] altMethods,
133 MethodHandle reflectiveField)
134 throws LambdaConversionException {
135 if (!caller.hasFullPrivilegeAccess()) {
136 throw new LambdaConversionException(String.format(
137 "Invalid caller: %s",
138 caller.lookupClass().getName()));
139 }
140 this.caller = caller;
141 this.targetClass = caller.lookupClass();
142 this.factoryType = factoryType;
143
144 this.interfaceClass = factoryType.returnType();
145
146 this.interfaceMethodName = interfaceMethodName;
147 this.interfaceMethodType = interfaceMethodType;
148
149 this.implementation = implementation;
150 this.implMethodType = implementation.type();
151 try {
152 this.implInfo = caller.revealDirect(implementation); // may throw SecurityException
153 } catch (IllegalArgumentException e) {
174 this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
175 } else {
176 this.implKind = REF_invokeSpecial;
177 }
178 break;
179 case REF_invokeStatic:
180 case REF_newInvokeSpecial:
181 // JDK-8172817: should use referenced class here for invokestatic, but we don't know what it was
182 this.implClass = implInfo.getDeclaringClass();
183 this.implKind = implInfo.getReferenceKind();
184 this.implIsInstanceMethod = false;
185 break;
186 default:
187 throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
188 }
189
190 this.dynamicMethodType = dynamicMethodType;
191 this.isSerializable = isSerializable;
192 this.altInterfaces = altInterfaces;
193 this.altMethods = altMethods;
194 this.quotableOpField = reflectiveField;
195 if (reflectiveField != null) {
196 // infer the method type associated with the intermediate representation of the
197 // quotable lambda. Since {@code factoryType} contains all the captured args
198 // we need to subtract the captured args that are required to invoke the lambda's
199 // bytecode. The type of {@code implementation} is useful here, as it corresponds to
200 // the signature of the emitted javac lambda implementation. From there, we need to
201 // drop all the dynamic arguments, which are obtained from {@code interfaceMethodType}.
202 this.quotableOpType = factoryType.dropParameterTypes(0,
203 implementation.type().parameterCount() - interfaceMethodType.parameterCount());
204 } else {
205 quotableOpType = null;
206 }
207
208 if (interfaceMethodName.isEmpty() ||
209 interfaceMethodName.indexOf('.') >= 0 ||
210 interfaceMethodName.indexOf(';') >= 0 ||
211 interfaceMethodName.indexOf('[') >= 0 ||
212 interfaceMethodName.indexOf('/') >= 0 ||
213 interfaceMethodName.indexOf('<') >= 0 ||
214 interfaceMethodName.indexOf('>') >= 0) {
215 throw new LambdaConversionException(String.format(
216 "Method name '%s' is not legal",
217 interfaceMethodName));
218 }
219
220 if (!interfaceClass.isInterface()) {
221 throw new LambdaConversionException(String.format(
222 "%s is not an interface",
223 interfaceClass.getName()));
224 }
225
226 for (Class<?> c : altInterfaces) {
227 if (!c.isInterface()) {
228 throw new LambdaConversionException(String.format(
229 "%s is not an interface",
230 c.getName()));
231 }
232 }
233
234 if (reflectiveField != null) {
235 try {
236 quotableOpFieldInfo = caller.revealDirect(reflectiveField); // may throw SecurityException
237 } catch (IllegalArgumentException e) {
238 throw new LambdaConversionException(implementation + " is not direct or cannot be cracked");
239 }
240 if (quotableOpFieldInfo.getReferenceKind() != REF_getField &&
241 quotableOpFieldInfo.getReferenceKind() != REF_getStatic) {
242 throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", quotableOpFieldInfo));
243 }
244 } else {
245 quotableOpFieldInfo = null;
246 }
247 }
248
249 /**
250 * Build the CallSite.
251 *
252 * @return a CallSite, which, when invoked, will return an instance of the
253 * functional interface
254 * @throws LambdaConversionException
255 */
256 abstract CallSite buildCallSite()
257 throws LambdaConversionException;
258
259 /**
260 * Check the meta-factory arguments for errors
261 * @throws LambdaConversionException if there are improper conversions
262 */
263 void validateMetafactoryArgs() throws LambdaConversionException {
264 // Check arity: captured + SAM == impl
265 final int implArity = implMethodType.parameterCount();
266 final int capturedArity = factoryType.parameterCount() - reflectiveCaptureCount();
267 final int samArity = interfaceMethodType.parameterCount();
268 final int dynamicArity = dynamicMethodType.parameterCount();
269 if (implArity != capturedArity + samArity) {
270 throw new LambdaConversionException(
271 String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
272 implIsInstanceMethod ? "instance" : "static", implInfo,
273 capturedArity, samArity, implArity));
274 }
275 if (dynamicArity != samArity) {
276 throw new LambdaConversionException(
277 String.format("Incorrect number of parameters for %s method %s; %d dynamic parameters, %d functional interface method parameters",
278 implIsInstanceMethod ? "instance" : "static", implInfo,
279 dynamicArity, samArity));
280 }
281 for (MethodType bridgeMT : altMethods) {
282 if (bridgeMT.parameterCount() != samArity) {
283 throw new LambdaConversionException(
284 String.format("Incorrect number of parameters for bridge signature %s; incompatible with %s",
285 bridgeMT, interfaceMethodType));
286 }
337 i, dynamicParamType, implParamType));
338 }
339 }
340
341 // Adaptation match: return type
342 Class<?> expectedType = dynamicMethodType.returnType();
343 Class<?> actualReturnType = implMethodType.returnType();
344 if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
345 throw new LambdaConversionException(
346 String.format("Type mismatch for lambda return: %s is not convertible to %s",
347 actualReturnType, expectedType));
348 }
349
350 // Check descriptors of generated methods
351 checkDescriptor(interfaceMethodType);
352 for (MethodType bridgeMT : altMethods) {
353 checkDescriptor(bridgeMT);
354 }
355 }
356
357 int reflectiveCaptureCount() {
358 return quotableOpType == null ? 0 : quotableOpType.parameterCount();
359 }
360
361 /** Validate that the given descriptor's types are compatible with {@code dynamicMethodType} **/
362 private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
363 for (int i = 0; i < dynamicMethodType.parameterCount(); i++) {
364 Class<?> dynamicParamType = dynamicMethodType.parameterType(i);
365 Class<?> descriptorParamType = descriptor.parameterType(i);
366 if (!descriptorParamType.isAssignableFrom(dynamicParamType)) {
367 String msg = String.format("Type mismatch for dynamic parameter %d: %s is not a subtype of %s",
368 i, dynamicParamType, descriptorParamType);
369 throw new LambdaConversionException(msg);
370 }
371 }
372
373 Class<?> dynamicReturnType = dynamicMethodType.returnType();
374 Class<?> descriptorReturnType = descriptor.returnType();
375 if (!isAdaptableToAsReturnStrict(dynamicReturnType, descriptorReturnType)) {
376 String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
377 dynamicReturnType, descriptorReturnType);
378 throw new LambdaConversionException(msg);
379 }
380 }
|