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.classfile.ClassBuilder;
30 import java.lang.reflect.Modifier;
31 import java.util.function.Function;
32
33 import static java.lang.invoke.MethodHandleInfo.*;
34 import static sun.invoke.util.Wrapper.forPrimitiveType;
35 import static sun.invoke.util.Wrapper.forWrapperType;
36 import static sun.invoke.util.Wrapper.isWrapperType;
37
38 /**
39 * Abstract implementation of a lambda metafactory which provides parameter
40 * unrolling and input validation.
41 *
42 * @see LambdaMetafactory
43 */
44 /* package */ abstract class AbstractValidatingLambdaMetafactory {
45
46 /*
47 * For context, the comments for the following fields are marked in quotes
48 * with their values, given this program:
49 * interface II<T> { Object foo(T x); }
50 * interface JJ<R extends Number> extends II<R> { }
51 * class CC { String impl(int i) { return "impl:"+i; }}
52 * class X {
53 * public static void main(String[] args) {
54 * JJ<Integer> iii = (new CC())::impl;
55 * System.out.printf(">>> %s\n", iii.foo(44));
56 * }}
57 */
58 final MethodHandles.Lookup caller; // The caller's lookup context
59 final Class<?> targetClass; // The class calling the meta-factory via invokedynamic "class X"
60 final MethodType factoryType; // The type of the invoked method "(CC)II"
61 final Class<?> interfaceClass; // The type of the returned instance "interface JJ"
62 final String interfaceMethodName; // Name of the method to implement "foo"
63 final MethodType interfaceMethodType; // Type of the method to implement "(Object)Object"
64 final MethodHandle implementation; // Raw method handle for the implementation method
65 final MethodType implMethodType; // Type of the implementation MethodHandle "(CC,int)String"
66 final MethodHandleInfo implInfo; // Info about the implementation method handle "MethodHandleInfo[5 CC.impl(int)String]"
67 final int implKind; // Invocation kind for implementation "5"=invokevirtual
68 final boolean implIsInstanceMethod; // Is the implementation an instance method "true"
69 final Class<?> implClass; // Class for referencing the implementation method "class CC"
70 final MethodType dynamicMethodType; // Dynamically checked method type "(Integer)Object"
71 final boolean isSerializable; // Should the returned instance be serializable
72 final Class<?>[] altInterfaces; // Additional interfaces to be implemented
73 final MethodType[] altMethods; // Signatures of additional methods to bridge
74 final Function<ClassBuilder, Object> finisher; // Function called to finish lambda class build process, returns additional class data (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 finisher Function called at the end of the lambda class build process
111 * that returns an additional object to append to the class data,
112 * may be (@code null}, may return {@code null}.
113 * @throws LambdaConversionException If any of the meta-factory protocol
114 * invariants are violated
115 */
116 AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller,
117 MethodType factoryType,
118 String interfaceMethodName,
119 MethodType interfaceMethodType,
120 MethodHandle implementation,
121 MethodType dynamicMethodType,
122 boolean isSerializable,
123 Class<?>[] altInterfaces,
124 MethodType[] altMethods,
125 Function<ClassBuilder, Object> finisher)
126 throws LambdaConversionException {
127 if (!caller.hasFullPrivilegeAccess()) {
128 throw new LambdaConversionException(String.format(
129 "Invalid caller: %s",
130 caller.lookupClass().getName()));
131 }
132 this.caller = caller;
133 this.targetClass = caller.lookupClass();
134 this.factoryType = factoryType;
135
136 this.interfaceClass = factoryType.returnType();
137
138 this.interfaceMethodName = interfaceMethodName;
139 this.interfaceMethodType = interfaceMethodType;
140
141 this.implementation = implementation;
142 this.implMethodType = implementation.type();
143 try {
144 this.implInfo = caller.revealDirect(implementation);
145 } catch (IllegalArgumentException e) {
146 throw new LambdaConversionException(implementation + " is not direct or cannot be cracked");
147 }
148 switch (implInfo.getReferenceKind()) {
149 case REF_invokeVirtual:
150 case REF_invokeInterface:
151 this.implClass = implMethodType.parameterType(0);
152 // reference kind reported by implInfo may not match implMethodType's first param
153 // Example: implMethodType is (Cloneable)String, implInfo is for Object.toString
154 this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
155 this.implIsInstanceMethod = true;
156 break;
157 case REF_invokeSpecial:
158 // JDK-8172817: should use referenced class here, but we don't know what it was
159 this.implClass = implInfo.getDeclaringClass();
160 this.implIsInstanceMethod = true;
161
162 // Classes compiled prior to dynamic nestmate support invoke a private instance
163 // method with REF_invokeSpecial. Newer classes use REF_invokeVirtual or
164 // REF_invokeInterface, and we can use that instruction in the lambda class.
165 if (targetClass == implClass && Modifier.isPrivate(implInfo.getModifiers())) {
166 this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
167 } else {
168 this.implKind = REF_invokeSpecial;
169 }
170 break;
171 case REF_invokeStatic:
172 case REF_newInvokeSpecial:
173 // JDK-8172817: should use referenced class here for invokestatic, but we don't know what it was
174 this.implClass = implInfo.getDeclaringClass();
175 this.implKind = implInfo.getReferenceKind();
176 this.implIsInstanceMethod = false;
177 break;
178 default:
179 throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
180 }
181
182 this.dynamicMethodType = dynamicMethodType;
183 this.isSerializable = isSerializable;
184 this.altInterfaces = altInterfaces;
185 this.altMethods = altMethods;
186 this.finisher = finisher;
187
188 if (interfaceMethodName.isEmpty() ||
189 interfaceMethodName.indexOf('.') >= 0 ||
190 interfaceMethodName.indexOf(';') >= 0 ||
191 interfaceMethodName.indexOf('[') >= 0 ||
192 interfaceMethodName.indexOf('/') >= 0 ||
193 interfaceMethodName.indexOf('<') >= 0 ||
194 interfaceMethodName.indexOf('>') >= 0) {
195 throw new LambdaConversionException(String.format(
196 "Method name '%s' is not legal",
197 interfaceMethodName));
198 }
199
200 if (!interfaceClass.isInterface()) {
201 throw new LambdaConversionException(String.format(
202 "%s is not an interface",
203 interfaceClass.getName()));
204 }
205
206 for (Class<?> c : altInterfaces) {
207 if (!c.isInterface()) {
208 throw new LambdaConversionException(String.format(
209 "%s is not an interface",
210 c.getName()));
211 }
212 }
213 }
214
215 /**
216 * Build the CallSite.
217 *
218 * @return a CallSite, which, when invoked, will return an instance of the
219 * functional interface
220 * @throws LambdaConversionException
221 */
222 abstract CallSite buildCallSite()
223 throws LambdaConversionException;
224
225 /**
226 * Check the meta-factory arguments for errors
227 * @throws LambdaConversionException if there are improper conversions
228 */
229 void validateMetafactoryArgs() throws LambdaConversionException {
230 // Check arity: captured + SAM == impl
231 final int implArity = implMethodType.parameterCount();
232 final int capturedArity = factoryType.parameterCount();
233 final int samArity = interfaceMethodType.parameterCount();
234 final int dynamicArity = dynamicMethodType.parameterCount();
235 if (implArity != capturedArity + samArity) {
236 throw new LambdaConversionException(
237 String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
238 implIsInstanceMethod ? "instance" : "static", implInfo,
239 capturedArity, samArity, implArity));
240 }
241 if (dynamicArity != samArity) {
242 throw new LambdaConversionException(
243 String.format("Incorrect number of parameters for %s method %s; %d dynamic parameters, %d functional interface method parameters",
244 implIsInstanceMethod ? "instance" : "static", implInfo,
245 dynamicArity, samArity));
246 }
247 for (MethodType bridgeMT : altMethods) {
248 if (bridgeMT.parameterCount() != samArity) {
249 throw new LambdaConversionException(
250 String.format("Incorrect number of parameters for bridge signature %s; incompatible with %s",
251 bridgeMT, interfaceMethodType));
252 }
253 }
254
255 // If instance: first captured arg (receiver) must be subtype of class where impl method is defined
256 final int capturedStart; // index of first non-receiver capture parameter in implMethodType
257 final int samStart; // index of first non-receiver sam parameter in implMethodType
258 if (implIsInstanceMethod) {
259 final Class<?> receiverClass;
260
261 // implementation is an instance method, adjust for receiver in captured variables / SAM arguments
262 if (capturedArity == 0) {
263 // receiver is function parameter
264 capturedStart = 0;
265 samStart = 1;
266 receiverClass = dynamicMethodType.parameterType(0);
267 } else {
268 // receiver is a captured variable
269 capturedStart = 1;
270 samStart = capturedArity;
271 receiverClass = factoryType.parameterType(0);
272 }
273
274 // check receiver type
275 if (!implClass.isAssignableFrom(receiverClass)) {
276 throw new LambdaConversionException(
277 String.format("Invalid receiver type %s; not a subtype of implementation type %s",
278 receiverClass, implClass));
279 }
280 } else {
281 // no receiver
282 capturedStart = 0;
283 samStart = capturedArity;
284 }
285
286 // Check for exact match on non-receiver captured arguments
287 for (int i=capturedStart; i<capturedArity; i++) {
288 Class<?> implParamType = implMethodType.parameterType(i);
289 Class<?> capturedParamType = factoryType.parameterType(i);
290 if (!capturedParamType.equals(implParamType)) {
291 throw new LambdaConversionException(
292 String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
293 i, capturedParamType, implParamType));
294 }
295 }
296 // Check for adaptation match on non-receiver SAM arguments
297 for (int i=samStart; i<implArity; i++) {
298 Class<?> implParamType = implMethodType.parameterType(i);
299 Class<?> dynamicParamType = dynamicMethodType.parameterType(i - capturedArity);
300 if (!isAdaptableTo(dynamicParamType, implParamType, true)) {
301 throw new LambdaConversionException(
302 String.format("Type mismatch for lambda argument %d: %s is not convertible to %s",
303 i, dynamicParamType, implParamType));
304 }
305 }
306
307 // Adaptation match: return type
308 Class<?> expectedType = dynamicMethodType.returnType();
309 Class<?> actualReturnType = implMethodType.returnType();
310 if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
311 throw new LambdaConversionException(
312 String.format("Type mismatch for lambda return: %s is not convertible to %s",
313 actualReturnType, expectedType));
314 }
315
316 // Check descriptors of generated methods
317 checkDescriptor(interfaceMethodType);
318 for (MethodType bridgeMT : altMethods) {
319 checkDescriptor(bridgeMT);
320 }
321 }
322
323 /** Validate that the given descriptor's types are compatible with {@code dynamicMethodType} **/
324 private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
325 for (int i = 0; i < dynamicMethodType.parameterCount(); i++) {
326 Class<?> dynamicParamType = dynamicMethodType.parameterType(i);
327 Class<?> descriptorParamType = descriptor.parameterType(i);
328 if (!descriptorParamType.isAssignableFrom(dynamicParamType)) {
329 String msg = String.format("Type mismatch for dynamic parameter %d: %s is not a subtype of %s",
330 i, dynamicParamType, descriptorParamType);
331 throw new LambdaConversionException(msg);
332 }
333 }
334
335 Class<?> dynamicReturnType = dynamicMethodType.returnType();
336 Class<?> descriptorReturnType = descriptor.returnType();
337 if (!isAdaptableToAsReturnStrict(dynamicReturnType, descriptorReturnType)) {
338 String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
339 dynamicReturnType, descriptorReturnType);
340 throw new LambdaConversionException(msg);
341 }
342 }
343
344 /**
345 * Check type adaptability for parameter types.
346 * @param fromType Type to convert from
347 * @param toType Type to convert to
348 * @param strict If true, do strict checks, else allow that fromType may be parameterized
349 * @return True if 'fromType' can be passed to an argument of 'toType'
350 */
351 private boolean isAdaptableTo(Class<?> fromType, Class<?> toType, boolean strict) {
352 if (fromType.equals(toType)) {
353 return true;
354 }
355 if (fromType.isPrimitive()) {
356 Wrapper wfrom = forPrimitiveType(fromType);
357 if (toType.isPrimitive()) {
358 // both are primitive: widening
359 Wrapper wto = forPrimitiveType(toType);
360 return wto.isConvertibleFrom(wfrom);
361 } else {
362 // from primitive to reference: boxing
363 return toType.isAssignableFrom(wfrom.wrapperType());
364 }
365 } else {
366 if (toType.isPrimitive()) {
367 // from reference to primitive: unboxing
368 Wrapper wfrom;
369 if (isWrapperType(fromType) && (wfrom = forWrapperType(fromType)).primitiveType().isPrimitive()) {
370 // fromType is a primitive wrapper; unbox+widen
371 Wrapper wto = forPrimitiveType(toType);
372 return wto.isConvertibleFrom(wfrom);
373 } else {
374 // must be convertible to primitive
375 return !strict;
376 }
377 } else {
378 // both are reference types: fromType should be a superclass of toType.
379 return !strict || toType.isAssignableFrom(fromType);
380 }
381 }
382 }
383
384 /**
385 * Check type adaptability for return types --
386 * special handling of void type) and parameterized fromType
387 * @return True if 'fromType' can be converted to 'toType'
388 */
389 private boolean isAdaptableToAsReturn(Class<?> fromType, Class<?> toType) {
390 return toType.equals(void.class)
391 || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false);
392 }
393 private boolean isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType) {
394 if (fromType.equals(void.class) || toType.equals(void.class)) return fromType.equals(toType);
395 else return isAdaptableTo(fromType, toType, true);
396 }
397
398
399 /*********** Logging support -- for debugging only, uncomment as needed
400 static final Executor logPool = Executors.newSingleThreadExecutor();
401 protected static void log(final String s) {
402 MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
403 @Override
404 public void run() {
405 System.out.println(s);
406 }
407 });
408 }
409
410 protected static void log(final String s, final Throwable e) {
411 MethodHandleProxyLambdaMetafactory.logPool.execute(new Runnable() {
412 @Override
413 public void run() {
414 System.out.println(s);
415 e.printStackTrace(System.out);
416 }
417 });
418 }
419 ***********************/
420
421 }