1/* 2 * Copyright (c) 2008, 2015, 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 26package java.lang.invoke; 27 28import jdk.internal.ref.CleanerFactory; 29import sun.invoke.util.Wrapper; 30 31import java.lang.invoke.MethodHandles.Lookup; 32import java.lang.reflect.Field; 33 34import static java.lang.invoke.MethodHandleNatives.Constants.*; 35import static java.lang.invoke.MethodHandleStatics.TRACE_METHOD_LINKAGE; 36import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; 37 38/** 39 * The JVM interface for the method handles package is all here. 40 * This is an interface internal and private to an implementation of JSR 292. 41 * <em>This class is not part of the JSR 292 standard.</em> 42 * @author jrose 43 */ 44class MethodHandleNatives { 45 46 private MethodHandleNatives() { } // static only 47 48 /// MemberName support 49 50 static native void init(MemberName self, Object ref); 51 static native void expand(MemberName self); 52 static native MemberName resolve(MemberName self, Class<?> caller) throws LinkageError, ClassNotFoundException; 53 static native int getMembers(Class<?> defc, String matchName, String matchSig, 54 int matchFlags, Class<?> caller, int skip, MemberName[] results); 55 56 /// Field layout queries parallel to jdk.internal.misc.Unsafe: 57 static native long objectFieldOffset(MemberName self); // e.g., returns vmindex 58 static native long staticFieldOffset(MemberName self); // e.g., returns vmindex 59 static native Object staticFieldBase(MemberName self); // e.g., returns clazz 60 static native Object getMemberVMInfo(MemberName self); // returns {vmindex,vmtarget} 61 62 /// CallSite support 63 64 /** Tell the JVM that we need to change the target of a CallSite. */ 65 static native void setCallSiteTargetNormal(CallSite site, MethodHandle target); 66 static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target); 67 68 /** Represents a context to track nmethod dependencies on CallSite instance target. */ 69 static class CallSiteContext implements Runnable { 70 //@Injected JVM_nmethodBucket* vmdependencies; 71 72 static CallSiteContext make(CallSite cs) { 73 final CallSiteContext newContext = new CallSiteContext(); 74 // CallSite instance is tracked by a Cleanable which clears native 75 // structures allocated for CallSite context. Though the CallSite can 76 // become unreachable, its Context is retained by the Cleanable instance 77 // (which is referenced from Cleaner instance which is referenced from 78 // CleanerFactory class) until cleanup is performed. 79 CleanerFactory.cleaner().register(cs, newContext); 80 return newContext; 81 } 82 83 @Override 84 public void run() { 85 MethodHandleNatives.clearCallSiteContext(this); 86 } 87 } 88 89 /** Invalidate all recorded nmethods. */ 90 private static native void clearCallSiteContext(CallSiteContext context); 91 92 private static native void registerNatives(); 93 static { 94 registerNatives(); 95 } 96 97 /** 98 * Compile-time constants go here. This collection exists not only for 99 * reference from clients, but also for ensuring the VM and JDK agree on the 100 * values of these constants (see {@link #verifyConstants()}). 101 */ 102 static class Constants { 103 Constants() { } // static only 104 105 static final int 106 MN_IS_METHOD = 0x00010000, // method (not constructor) 107 MN_IS_CONSTRUCTOR = 0x00020000, // constructor 108 MN_IS_FIELD = 0x00040000, // field 109 MN_IS_TYPE = 0x00080000, // nested type 110 MN_CALLER_SENSITIVE = 0x00100000, // @CallerSensitive annotation detected 111 MN_REFERENCE_KIND_SHIFT = 24, // refKind 112 MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT, 113 // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers: 114 MN_SEARCH_SUPERCLASSES = 0x00100000, 115 MN_SEARCH_INTERFACES = 0x00200000; 116 117 /** 118 * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries. 119 */ 120 static final byte 121 REF_NONE = 0, // null value 122 REF_getField = 1, 123 REF_getStatic = 2, 124 REF_putField = 3, 125 REF_putStatic = 4, 126 REF_invokeVirtual = 5, 127 REF_invokeStatic = 6, 128 REF_invokeSpecial = 7, 129 REF_newInvokeSpecial = 8, 130 REF_invokeInterface = 9, 131 REF_LIMIT = 10; 132 } 133 134 static boolean refKindIsValid(int refKind) { 135 return (refKind > REF_NONE && refKind < REF_LIMIT); 136 } 137 static boolean refKindIsField(byte refKind) { 138 assert(refKindIsValid(refKind)); 139 return (refKind <= REF_putStatic); 140 } 141 static boolean refKindIsGetter(byte refKind) { 142 assert(refKindIsValid(refKind)); 143 return (refKind <= REF_getStatic); 144 } 145 static boolean refKindIsSetter(byte refKind) { 146 return refKindIsField(refKind) && !refKindIsGetter(refKind); 147 } 148 static boolean refKindIsMethod(byte refKind) { 149 return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial); 150 } 151 static boolean refKindIsConstructor(byte refKind) { 152 return (refKind == REF_newInvokeSpecial); 153 } 154 static boolean refKindHasReceiver(byte refKind) { 155 assert(refKindIsValid(refKind)); 156 return (refKind & 1) != 0; 157 } 158 static boolean refKindIsStatic(byte refKind) { 159 return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial); 160 } 161 static boolean refKindDoesDispatch(byte refKind) { 162 assert(refKindIsValid(refKind)); 163 return (refKind == REF_invokeVirtual || 164 refKind == REF_invokeInterface); 165 } 166 static { 167 final int HR_MASK = ((1 << REF_getField) | 168 (1 << REF_putField) | 169 (1 << REF_invokeVirtual) | 170 (1 << REF_invokeSpecial) | 171 (1 << REF_invokeInterface) 172 ); 173 for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) { 174 assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind; 175 } 176 } 177 static String refKindName(byte refKind) { 178 assert(refKindIsValid(refKind)); 179 switch (refKind) { 180 case REF_getField: return "getField"; 181 case REF_getStatic: return "getStatic"; 182 case REF_putField: return "putField"; 183 case REF_putStatic: return "putStatic"; 184 case REF_invokeVirtual: return "invokeVirtual"; 185 case REF_invokeStatic: return "invokeStatic"; 186 case REF_invokeSpecial: return "invokeSpecial"; 187 case REF_newInvokeSpecial: return "newInvokeSpecial"; 188 case REF_invokeInterface: return "invokeInterface"; 189 default: return "REF_???"; 190 } 191 } 192 193 private static native int getNamedCon(int which, Object[] name); 194 static boolean verifyConstants() { 195 Object[] box = { null }; 196 for (int i = 0; ; i++) { 197 box[0] = null; 198 int vmval = getNamedCon(i, box); 199 if (box[0] == null) break; 200 String name = (String) box[0]; 201 try { 202 Field con = Constants.class.getDeclaredField(name); 203 int jval = con.getInt(null); 204 if (jval == vmval) continue; 205 String err = (name+": JVM has "+vmval+" while Java has "+jval); 206 if (name.equals("CONV_OP_LIMIT")) { 207 System.err.println("warning: "+err); 208 continue; 209 } 210 throw new InternalError(err); 211 } catch (NoSuchFieldException | IllegalAccessException ex) { 212 String err = (name+": JVM has "+vmval+" which Java does not define"); 213 // ignore exotic ops the JVM cares about; we just wont issue them 214 //System.err.println("warning: "+err); 215 continue; 216 } 217 } 218 return true; 219 } 220 static { 221 assert(verifyConstants()); 222 } 223 224 // Up-calls from the JVM. 225 // These must NOT be public. 226 227 /** 228 * The JVM is linking an invokedynamic instruction. Create a reified call site for it. 229 */ 230 static MemberName linkCallSite(Object callerObj, 231 Object bootstrapMethodObj, 232 Object nameObj, Object typeObj, 233 Object staticArguments, 234 Object[] appendixResult) { 235 MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj; 236 Class<?> caller = (Class<?>)callerObj; 237 String name = nameObj.toString().intern(); 238 MethodType type = (MethodType)typeObj; 239 if (!TRACE_METHOD_LINKAGE) 240 return linkCallSiteImpl(caller, bootstrapMethod, name, type, 241 staticArguments, appendixResult); 242 return linkCallSiteTracing(caller, bootstrapMethod, name, type, 243 staticArguments, appendixResult); 244 } 245 static MemberName linkCallSiteImpl(Class<?> caller, 246 MethodHandle bootstrapMethod, 247 String name, MethodType type, 248 Object staticArguments, 249 Object[] appendixResult) { 250 CallSite callSite = CallSite.makeSite(bootstrapMethod, 251 name, 252 type, 253 staticArguments, 254 caller); 255 if (callSite instanceof ConstantCallSite) { 256 appendixResult[0] = callSite.dynamicInvoker(); 257 return Invokers.linkToTargetMethod(type); 258 } else { 259 appendixResult[0] = callSite; 260 return Invokers.linkToCallSiteMethod(type); 261 } 262 } 263 // Tracing logic: 264 static MemberName linkCallSiteTracing(Class<?> caller, 265 MethodHandle bootstrapMethod, 266 String name, MethodType type, 267 Object staticArguments, 268 Object[] appendixResult) { 269 Object bsmReference = bootstrapMethod.internalMemberName(); 270 if (bsmReference == null) bsmReference = bootstrapMethod; 271 Object staticArglist = (staticArguments instanceof Object[] ? 272 java.util.Arrays.asList((Object[]) staticArguments) : 273 staticArguments); 274 System.out.println("linkCallSite "+caller.getName()+" "+ 275 bsmReference+" "+ 276 name+type+"/"+staticArglist); 277 try { 278 MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type, 279 staticArguments, appendixResult); 280 System.out.println("linkCallSite => "+res+" + "+appendixResult[0]); 281 return res; 282 } catch (Throwable ex) { 283 System.out.println("linkCallSite => throw "+ex); 284 throw ex; 285 } 286 } 287 288 /** 289 * The JVM wants a pointer to a MethodType. Oblige it by finding or creating one. 290 */ 291 static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) { 292 return MethodType.makeImpl(rtype, ptypes, true); 293 } 294 295 /** 296 * The JVM wants to link a call site that requires a dynamic type check. 297 * Name is a type-checking invoker, invokeExact or invoke. 298 * Return a JVM method (MemberName) to handle the invoking. 299 * The method assumes the following arguments on the stack: 300 * 0: the method handle being invoked 301 * 1-N: the arguments to the method handle invocation 302 * N+1: an optional, implicitly added argument (typically the given MethodType) 303 * <p> 304 * The nominal method at such a call site is an instance of 305 * a signature-polymorphic method (see @PolymorphicSignature). 306 * Such method instances are user-visible entities which are 307 * "split" from the generic placeholder method in {@code MethodHandle}. 308 * (Note that the placeholder method is not identical with any of 309 * its instances. If invoked reflectively, is guaranteed to throw an 310 * {@code UnsupportedOperationException}.) 311 * If the signature-polymorphic method instance is ever reified, 312 * it appears as a "copy" of the original placeholder 313 * (a native final member of {@code MethodHandle}) except 314 * that its type descriptor has shape required by the instance, 315 * and the method instance is <em>not</em> varargs. 316 * The method instance is also marked synthetic, since the 317 * method (by definition) does not appear in Java source code. 318 * <p> 319 * The JVM is allowed to reify this method as instance metadata. 320 * For example, {@code invokeBasic} is always reified. 321 * But the JVM may instead call {@code linkMethod}. 322 * If the result is an * ordered pair of a {@code (method, appendix)}, 323 * the method gets all the arguments (0..N inclusive) 324 * plus the appendix (N+1), and uses the appendix to complete the call. 325 * In this way, one reusable method (called a "linker method") 326 * can perform the function of any number of polymorphic instance 327 * methods. 328 * <p> 329 * Linker methods are allowed to be weakly typed, with any or 330 * all references rewritten to {@code Object} and any primitives 331 * (except {@code long}/{@code float}/{@code double}) 332 * rewritten to {@code int}. 333 * A linker method is trusted to return a strongly typed result, 334 * according to the specific method type descriptor of the 335 * signature-polymorphic instance it is emulating. 336 * This can involve (as necessary) a dynamic check using 337 * data extracted from the appendix argument. 338 * <p> 339 * The JVM does not inspect the appendix, other than to pass 340 * it verbatim to the linker method at every call. 341 * This means that the JDK runtime has wide latitude 342 * for choosing the shape of each linker method and its 343 * corresponding appendix. 344 * Linker methods should be generated from {@code LambdaForm}s 345 * so that they do not become visible on stack traces. 346 * <p> 347 * The {@code linkMethod} call is free to omit the appendix 348 * (returning null) and instead emulate the required function 349 * completely in the linker method. 350 * As a corner case, if N==255, no appendix is possible. 351 * In this case, the method returned must be custom-generated to 352 * to perform any needed type checking. 353 * <p> 354 * If the JVM does not reify a method at a call site, but instead 355 * calls {@code linkMethod}, the corresponding call represented 356 * in the bytecodes may mention a valid method which is not 357 * representable with a {@code MemberName}. 358 * Therefore, use cases for {@code linkMethod} tend to correspond to 359 * special cases in reflective code such as {@code findVirtual} 360 * or {@code revealDirect}. 361 */ 362 static MemberName linkMethod(Class<?> callerClass, int refKind, 363 Class<?> defc, String name, Object type, 364 Object[] appendixResult) { 365 if (!TRACE_METHOD_LINKAGE) 366 return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult); 367 return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult); 368 } 369 static MemberName linkMethodImpl(Class<?> callerClass, int refKind, 370 Class<?> defc, String name, Object type, 371 Object[] appendixResult) { 372 try { 373 if (refKind == REF_invokeVirtual) { 374 if (defc == MethodHandle.class) { 375 return Invokers.methodHandleInvokeLinkerMethod( 376 name, fixMethodType(callerClass, type), appendixResult); 377 } else if (defc == VarHandle.class) { 378 return varHandleOperationLinkerMethod( 379 name, fixMethodType(callerClass, type), appendixResult); 380 } 381 } 382 } catch (Error e) { 383 // Pass through an Error, including say StackOverflowError or 384 // OutOfMemoryError 385 throw e; 386 } catch (Throwable ex) { 387 // Wrap anything else in LinkageError 388 throw new LinkageError(ex.getMessage(), ex); 389 } 390 throw new LinkageError("no such method "+defc.getName()+"."+name+type); 391 } 392 private static MethodType fixMethodType(Class<?> callerClass, Object type) { 393 if (type instanceof MethodType) 394 return (MethodType) type; 395 else 396 return MethodType.fromDescriptor((String)type, callerClass.getClassLoader()); 397 } 398 // Tracing logic: 399 static MemberName linkMethodTracing(Class<?> callerClass, int refKind, 400 Class<?> defc, String name, Object type, 401 Object[] appendixResult) { 402 System.out.println("linkMethod "+defc.getName()+"."+ 403 name+type+"/"+Integer.toHexString(refKind)); 404 try { 405 MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult); 406 System.out.println("linkMethod => "+res+" + "+appendixResult[0]); 407 return res; 408 } catch (Throwable ex) { 409 System.out.println("linkMethod => throw "+ex); 410 throw ex; 411 } 412 } 413 414 /** 415 * Obtain the method to link to the VarHandle operation. 416 * This method is located here and not in Invokers to avoid 417 * intializing that and other classes early on in VM bootup. 418 */ 419 private static MemberName varHandleOperationLinkerMethod(String name, 420 MethodType mtype, 421 Object[] appendixResult) { 422 // Get the signature method type 423 MethodType sigType = mtype.basicType(); 424 425 // Get the access kind from the method name 426 VarHandle.AccessMode ak; 427 try { 428 ak = VarHandle.AccessMode.valueFromMethodName(name); 429 } catch (IllegalArgumentException e) { 430 throw MethodHandleStatics.newInternalError(e); 431 } 432 433 // If not polymorphic in the return type, such as the compareAndSet 434 // methods that return boolean 435 if (ak.at.isMonomorphicInReturnType) { 436 if (ak.at.returnType != mtype.returnType()) { 437 // The caller contains a different return type than that 438 // defined by the method 439 throw newNoSuchMethodErrorOnVarHandle(name, mtype); 440 } 441 // Adjust the return type of the signature method type 442 sigType = sigType.changeReturnType(ak.at.returnType); 443 } 444 445 // Get the guard method type for linking 446 MethodType guardType = sigType 447 // VarHandle at start 448 .insertParameterTypes(0, VarHandle.class) 449 // Access descriptor at end 450 .appendParameterTypes(VarHandle.AccessDescriptor.class); 451 452 // Create the appendix descriptor constant 453 VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal()); 454 appendixResult[0] = ad; 455 456 if (MethodHandleStatics.VAR_HANDLE_GUARDS) { 457 MemberName linker = new MemberName( 458 VarHandleGuards.class, "guard_" + getVarHandleMethodSignature(sigType), 459 guardType, REF_invokeStatic); 460 461 linker = MemberName.getFactory().resolveOrNull(REF_invokeStatic, linker, 462 VarHandleGuards.class); 463 if (linker != null) { 464 return linker; 465 } 466 // Fall back to lambda form linkage if guard method is not available 467 // TODO Optionally log fallback ? 468 } 469 return Invokers.varHandleInvokeLinkerMethod(name, mtype); 470 } 471 static String getVarHandleMethodSignature(MethodType mt) { 472 StringBuilder sb = new StringBuilder(mt.parameterCount() + 2); 473 474 for (int i = 0; i < mt.parameterCount(); i++) { 475 Class<?> pt = mt.parameterType(i); 476 sb.append(getCharType(pt)); 477 } 478 sb.append('_').append(getCharType(mt.returnType())); 479 return sb.toString(); 480 } 481 static char getCharType(Class<?> pt) { 482 return Wrapper.forBasicType(pt).basicTypeChar(); 483 } 484 static NoSuchMethodError newNoSuchMethodErrorOnVarHandle(String name, MethodType mtype) { 485 return new NoSuchMethodError("VarHandle." + name + mtype); 486 } 487 488 /** 489 * The JVM is resolving a CONSTANT_MethodHandle CP entry. And it wants our help. 490 * It will make an up-call to this method. (Do not change the name or signature.) 491 * The type argument is a Class for field requests and a MethodType for non-fields. 492 * <p> 493 * Recent versions of the JVM may also pass a resolved MemberName for the type. 494 * In that case, the name is ignored and may be null. 495 */ 496 static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind, 497 Class<?> defc, String name, Object type) { 498 try { 499 Lookup lookup = IMPL_LOOKUP.in(callerClass); 500 assert(refKindIsValid(refKind)); 501 return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type); 502 } catch (IllegalAccessException ex) { 503 Throwable cause = ex.getCause(); 504 if (cause instanceof AbstractMethodError) { 505 throw (AbstractMethodError) cause; 506 } else { 507 Error err = new IllegalAccessError(ex.getMessage()); 508 throw initCauseFrom(err, ex); 509 } 510 } catch (NoSuchMethodException ex) { 511 Error err = new NoSuchMethodError(ex.getMessage()); 512 throw initCauseFrom(err, ex); 513 } catch (NoSuchFieldException ex) { 514 Error err = new NoSuchFieldError(ex.getMessage()); 515 throw initCauseFrom(err, ex); 516 } catch (ReflectiveOperationException ex) { 517 Error err = new IncompatibleClassChangeError(); 518 throw initCauseFrom(err, ex); 519 } 520 } 521 522 /** 523 * Use best possible cause for err.initCause(), substituting the 524 * cause for err itself if the cause has the same (or better) type. 525 */ 526 private static Error initCauseFrom(Error err, Exception ex) { 527 Throwable th = ex.getCause(); 528 if (err.getClass().isInstance(th)) 529 return (Error) th; 530 err.initCause(th == null ? ex : th); 531 return err; 532 } 533 534 /** 535 * Is this method a caller-sensitive method? 536 * I.e., does it call Reflection.getCallerClass or a similar method 537 * to ask about the identity of its caller? 538 */ 539 static boolean isCallerSensitive(MemberName mem) { 540 if (!mem.isInvocable()) return false; // fields are not caller sensitive 541 542 return mem.isCallerSensitive() || canBeCalledVirtual(mem); 543 } 544 545 static boolean canBeCalledVirtual(MemberName mem) { 546 assert(mem.isInvocable()); 547 Class<?> defc = mem.getDeclaringClass(); 548 switch (mem.getName()) { 549 case "checkMemberAccess": 550 return canBeCalledVirtual(mem, java.lang.SecurityManager.class); 551 case "getContextClassLoader": 552 return canBeCalledVirtual(mem, java.lang.Thread.class); 553 } 554 return false; 555 } 556 557 static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) { 558 Class<?> symbolicRefClass = symbolicRef.getDeclaringClass(); 559 if (symbolicRefClass == definingClass) return true; 560 if (symbolicRef.isStatic() || symbolicRef.isPrivate()) return false; 561 return (definingClass.isAssignableFrom(symbolicRefClass) || // Msym overrides Mdef 562 symbolicRefClass.isInterface()); // Mdef implements Msym 563 } 564} 565