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