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