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