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