1 /* 2 * Copyright (c) 2008, 2018, 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 jdk.internal.misc.Unsafe; 29 import jdk.internal.vm.annotation.ForceInline; 30 import jdk.internal.vm.annotation.Stable; 31 import sun.invoke.util.ValueConversions; 32 import sun.invoke.util.VerifyAccess; 33 import sun.invoke.util.VerifyType; 34 import sun.invoke.util.Wrapper; 35 36 import java.lang.ref.WeakReference; 37 import java.util.Arrays; 38 import java.util.Objects; 39 40 import static java.lang.invoke.LambdaForm.*; 41 import static java.lang.invoke.LambdaForm.Kind.*; 42 import static java.lang.invoke.MethodHandleNatives.Constants.*; 43 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 44 import static java.lang.invoke.MethodHandleStatics.newInternalError; 45 import static java.lang.invoke.MethodTypeForm.*; 46 47 /** 48 * The flavor of method handle which implements a constant reference 49 * to a class member. 50 * @author jrose 51 */ 52 class DirectMethodHandle extends MethodHandle { 53 final MemberName member; 54 55 // Constructors and factory methods in this class *must* be package scoped or private. DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member)56 private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member) { 57 super(mtype, form); 58 if (!member.isResolved()) throw new InternalError(); 59 60 if (member.getDeclaringClass().isInterface() && 61 member.getReferenceKind() == REF_invokeInterface && 62 member.isMethod() && !member.isAbstract()) { 63 // Check for corner case: invokeinterface of Object method 64 MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind()); 65 m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null); 66 if (m != null && m.isPublic()) { 67 assert(member.getReferenceKind() == m.getReferenceKind()); // else this.form is wrong 68 member = m; 69 } 70 } 71 72 this.member = member; 73 } 74 75 // Factory methods: make(byte refKind, Class<?> refc, MemberName member, Class<?> callerClass)76 static DirectMethodHandle make(byte refKind, Class<?> refc, MemberName member, Class<?> callerClass) { 77 MethodType mtype = member.getMethodOrFieldType(); 78 if (!member.isStatic()) { 79 if (!member.getDeclaringClass().isAssignableFrom(refc) || member.isConstructor()) 80 throw new InternalError(member.toString()); 81 mtype = mtype.insertParameterTypes(0, refc); 82 } 83 if (!member.isField()) { 84 // refKind reflects the original type of lookup via findSpecial or 85 // findVirtual etc. 86 switch (refKind) { 87 case REF_invokeSpecial: { 88 member = member.asSpecial(); 89 // if caller is an interface we need to adapt to get the 90 // receiver check inserted 91 if (callerClass == null) { 92 throw new InternalError("callerClass must not be null for REF_invokeSpecial"); 93 } 94 LambdaForm lform = preparedLambdaForm(member, callerClass.isInterface()); 95 return new Special(mtype, lform, member, callerClass); 96 } 97 case REF_invokeInterface: { 98 // for interfaces we always need the receiver typecheck, 99 // so we always pass 'true' to ensure we adapt if needed 100 // to include the REF_invokeSpecial case 101 LambdaForm lform = preparedLambdaForm(member, true); 102 return new Interface(mtype, lform, member, refc); 103 } 104 default: { 105 LambdaForm lform = preparedLambdaForm(member); 106 return new DirectMethodHandle(mtype, lform, member); 107 } 108 } 109 } else { 110 LambdaForm lform = preparedFieldLambdaForm(member); 111 if (member.isStatic()) { 112 long offset = MethodHandleNatives.staticFieldOffset(member); 113 Object base = MethodHandleNatives.staticFieldBase(member); 114 return new StaticAccessor(mtype, lform, member, base, offset); 115 } else { 116 long offset = MethodHandleNatives.objectFieldOffset(member); 117 assert(offset == (int)offset); 118 return new Accessor(mtype, lform, member, (int)offset); 119 } 120 } 121 } make(Class<?> refc, MemberName member)122 static DirectMethodHandle make(Class<?> refc, MemberName member) { 123 byte refKind = member.getReferenceKind(); 124 if (refKind == REF_invokeSpecial) 125 refKind = REF_invokeVirtual; 126 return make(refKind, refc, member, null /* no callerClass context */); 127 } make(MemberName member)128 static DirectMethodHandle make(MemberName member) { 129 if (member.isConstructor()) 130 return makeAllocator(member); 131 return make(member.getDeclaringClass(), member); 132 } makeAllocator(MemberName ctor)133 private static DirectMethodHandle makeAllocator(MemberName ctor) { 134 assert(ctor.isConstructor() && ctor.getName().equals("<init>")); 135 Class<?> instanceClass = ctor.getDeclaringClass(); 136 ctor = ctor.asConstructor(); 137 assert(ctor.isConstructor() && ctor.getReferenceKind() == REF_newInvokeSpecial) : ctor; 138 MethodType mtype = ctor.getMethodType().changeReturnType(instanceClass); 139 LambdaForm lform = preparedLambdaForm(ctor); 140 MemberName init = ctor.asSpecial(); 141 assert(init.getMethodType().returnType() == void.class); 142 return new Constructor(mtype, lform, ctor, init, instanceClass); 143 } 144 145 @Override rebind()146 BoundMethodHandle rebind() { 147 return BoundMethodHandle.makeReinvoker(this); 148 } 149 150 @Override copyWith(MethodType mt, LambdaForm lf)151 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 152 assert(this.getClass() == DirectMethodHandle.class); // must override in subclasses 153 return new DirectMethodHandle(mt, lf, member); 154 } 155 156 @Override internalProperties()157 String internalProperties() { 158 return "\n& DMH.MN="+internalMemberName(); 159 } 160 161 //// Implementation methods. 162 @Override 163 @ForceInline internalMemberName()164 MemberName internalMemberName() { 165 return member; 166 } 167 168 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 169 170 /** 171 * Create a LF which can invoke the given method. 172 * Cache and share this structure among all methods with 173 * the same basicType and refKind. 174 */ preparedLambdaForm(MemberName m, boolean adaptToSpecialIfc)175 private static LambdaForm preparedLambdaForm(MemberName m, boolean adaptToSpecialIfc) { 176 assert(m.isInvocable()) : m; // call preparedFieldLambdaForm instead 177 MethodType mtype = m.getInvocationType().basicType(); 178 assert(!m.isMethodHandleInvoke()) : m; 179 int which; 180 // MemberName.getReferenceKind represents the JVM optimized form of the call 181 // as distinct from the "kind" passed to DMH.make which represents the original 182 // bytecode-equivalent request. Specifically private/final methods that use a direct 183 // call have getReferenceKind adapted to REF_invokeSpecial, even though the actual 184 // invocation mode may be invokevirtual or invokeinterface. 185 switch (m.getReferenceKind()) { 186 case REF_invokeVirtual: which = LF_INVVIRTUAL; break; 187 case REF_invokeStatic: which = LF_INVSTATIC; break; 188 case REF_invokeSpecial: which = LF_INVSPECIAL; break; 189 case REF_invokeInterface: which = LF_INVINTERFACE; break; 190 case REF_newInvokeSpecial: which = LF_NEWINVSPECIAL; break; 191 default: throw new InternalError(m.toString()); 192 } 193 if (which == LF_INVSTATIC && shouldBeInitialized(m)) { 194 // precompute the barrier-free version: 195 preparedLambdaForm(mtype, which); 196 which = LF_INVSTATIC_INIT; 197 } 198 if (which == LF_INVSPECIAL && adaptToSpecialIfc) { 199 which = LF_INVSPECIAL_IFC; 200 } 201 LambdaForm lform = preparedLambdaForm(mtype, which); 202 maybeCompile(lform, m); 203 assert(lform.methodType().dropParameterTypes(0, 1) 204 .equals(m.getInvocationType().basicType())) 205 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 206 return lform; 207 } 208 preparedLambdaForm(MemberName m)209 private static LambdaForm preparedLambdaForm(MemberName m) { 210 return preparedLambdaForm(m, false); 211 } 212 preparedLambdaForm(MethodType mtype, int which)213 private static LambdaForm preparedLambdaForm(MethodType mtype, int which) { 214 LambdaForm lform = mtype.form().cachedLambdaForm(which); 215 if (lform != null) return lform; 216 lform = makePreparedLambdaForm(mtype, which); 217 return mtype.form().setCachedLambdaForm(which, lform); 218 } 219 makePreparedLambdaForm(MethodType mtype, int which)220 static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) { 221 boolean needsInit = (which == LF_INVSTATIC_INIT); 222 boolean doesAlloc = (which == LF_NEWINVSPECIAL); 223 boolean needsReceiverCheck = (which == LF_INVINTERFACE || 224 which == LF_INVSPECIAL_IFC); 225 226 String linkerName; 227 LambdaForm.Kind kind; 228 switch (which) { 229 case LF_INVVIRTUAL: linkerName = "linkToVirtual"; kind = DIRECT_INVOKE_VIRTUAL; break; 230 case LF_INVSTATIC: linkerName = "linkToStatic"; kind = DIRECT_INVOKE_STATIC; break; 231 case LF_INVSTATIC_INIT:linkerName = "linkToStatic"; kind = DIRECT_INVOKE_STATIC_INIT; break; 232 case LF_INVSPECIAL_IFC:linkerName = "linkToSpecial"; kind = DIRECT_INVOKE_SPECIAL_IFC; break; 233 case LF_INVSPECIAL: linkerName = "linkToSpecial"; kind = DIRECT_INVOKE_SPECIAL; break; 234 case LF_INVINTERFACE: linkerName = "linkToInterface"; kind = DIRECT_INVOKE_INTERFACE; break; 235 case LF_NEWINVSPECIAL: linkerName = "linkToSpecial"; kind = DIRECT_NEW_INVOKE_SPECIAL; break; 236 default: throw new InternalError("which="+which); 237 } 238 239 MethodType mtypeWithArg = mtype.appendParameterTypes(MemberName.class); 240 if (doesAlloc) 241 mtypeWithArg = mtypeWithArg 242 .insertParameterTypes(0, Object.class) // insert newly allocated obj 243 .changeReturnType(void.class); // <init> returns void 244 MemberName linker = new MemberName(MethodHandle.class, linkerName, mtypeWithArg, REF_invokeStatic); 245 try { 246 linker = IMPL_NAMES.resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class); 247 } catch (ReflectiveOperationException ex) { 248 throw newInternalError(ex); 249 } 250 final int DMH_THIS = 0; 251 final int ARG_BASE = 1; 252 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 253 int nameCursor = ARG_LIMIT; 254 final int NEW_OBJ = (doesAlloc ? nameCursor++ : -1); 255 final int GET_MEMBER = nameCursor++; 256 final int CHECK_RECEIVER = (needsReceiverCheck ? nameCursor++ : -1); 257 final int LINKER_CALL = nameCursor++; 258 Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); 259 assert(names.length == nameCursor); 260 if (doesAlloc) { 261 // names = { argx,y,z,... new C, init method } 262 names[NEW_OBJ] = new Name(getFunction(NF_allocateInstance), names[DMH_THIS]); 263 names[GET_MEMBER] = new Name(getFunction(NF_constructorMethod), names[DMH_THIS]); 264 } else if (needsInit) { 265 names[GET_MEMBER] = new Name(getFunction(NF_internalMemberNameEnsureInit), names[DMH_THIS]); 266 } else { 267 names[GET_MEMBER] = new Name(getFunction(NF_internalMemberName), names[DMH_THIS]); 268 } 269 assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]); 270 Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class); 271 if (needsReceiverCheck) { 272 names[CHECK_RECEIVER] = new Name(getFunction(NF_checkReceiver), names[DMH_THIS], names[ARG_BASE]); 273 outArgs[0] = names[CHECK_RECEIVER]; 274 } 275 assert(outArgs[outArgs.length-1] == names[GET_MEMBER]); // look, shifted args! 276 int result = LAST_RESULT; 277 if (doesAlloc) { 278 assert(outArgs[outArgs.length-2] == names[NEW_OBJ]); // got to move this one 279 System.arraycopy(outArgs, 0, outArgs, 1, outArgs.length-2); 280 outArgs[0] = names[NEW_OBJ]; 281 result = NEW_OBJ; 282 } 283 names[LINKER_CALL] = new Name(linker, outArgs); 284 LambdaForm lform = new LambdaForm(ARG_LIMIT, names, result, kind); 285 286 // This is a tricky bit of code. Don't send it through the LF interpreter. 287 lform.compileToBytecode(); 288 return lform; 289 } 290 findDirectMethodHandle(Name name)291 /* assert */ static Object findDirectMethodHandle(Name name) { 292 if (name.function.equals(getFunction(NF_internalMemberName)) || 293 name.function.equals(getFunction(NF_internalMemberNameEnsureInit)) || 294 name.function.equals(getFunction(NF_constructorMethod))) { 295 assert(name.arguments.length == 1); 296 return name.arguments[0]; 297 } 298 return null; 299 } 300 maybeCompile(LambdaForm lform, MemberName m)301 private static void maybeCompile(LambdaForm lform, MemberName m) { 302 if (lform.vmentry == null && VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class)) 303 // Help along bootstrapping... 304 lform.compileToBytecode(); 305 } 306 307 /** Static wrapper for DirectMethodHandle.internalMemberName. */ 308 @ForceInline 309 /*non-public*/ internalMemberName(Object mh)310 static Object internalMemberName(Object mh) { 311 return ((DirectMethodHandle)mh).member; 312 } 313 314 /** Static wrapper for DirectMethodHandle.internalMemberName. 315 * This one also forces initialization. 316 */ 317 /*non-public*/ internalMemberNameEnsureInit(Object mh)318 static Object internalMemberNameEnsureInit(Object mh) { 319 DirectMethodHandle dmh = (DirectMethodHandle)mh; 320 dmh.ensureInitialized(); 321 return dmh.member; 322 } 323 324 /*non-public*/ shouldBeInitialized(MemberName member)325 static boolean shouldBeInitialized(MemberName member) { 326 switch (member.getReferenceKind()) { 327 case REF_invokeStatic: 328 case REF_getStatic: 329 case REF_putStatic: 330 case REF_newInvokeSpecial: 331 break; 332 default: 333 // No need to initialize the class on this kind of member. 334 return false; 335 } 336 Class<?> cls = member.getDeclaringClass(); 337 if (cls == ValueConversions.class || 338 cls == MethodHandleImpl.class || 339 cls == Invokers.class) { 340 // These guys have lots of <clinit> DMH creation but we know 341 // the MHs will not be used until the system is booted. 342 return false; 343 } 344 if (VerifyAccess.isSamePackage(MethodHandle.class, cls) || 345 VerifyAccess.isSamePackage(ValueConversions.class, cls)) { 346 // It is a system class. It is probably in the process of 347 // being initialized, but we will help it along just to be safe. 348 if (UNSAFE.shouldBeInitialized(cls)) { 349 UNSAFE.ensureClassInitialized(cls); 350 } 351 return false; 352 } 353 return UNSAFE.shouldBeInitialized(cls); 354 } 355 356 private static class EnsureInitialized extends ClassValue<WeakReference<Thread>> { 357 @Override computeValue(Class<?> type)358 protected WeakReference<Thread> computeValue(Class<?> type) { 359 UNSAFE.ensureClassInitialized(type); 360 if (UNSAFE.shouldBeInitialized(type)) 361 // If the previous call didn't block, this can happen. 362 // We are executing inside <clinit>. 363 return new WeakReference<>(Thread.currentThread()); 364 return null; 365 } 366 static final EnsureInitialized INSTANCE = new EnsureInitialized(); 367 } 368 ensureInitialized()369 private void ensureInitialized() { 370 if (checkInitialized(member)) { 371 // The coast is clear. Delete the <clinit> barrier. 372 if (member.isField()) 373 updateForm(preparedFieldLambdaForm(member)); 374 else 375 updateForm(preparedLambdaForm(member)); 376 } 377 } checkInitialized(MemberName member)378 private static boolean checkInitialized(MemberName member) { 379 Class<?> defc = member.getDeclaringClass(); 380 WeakReference<Thread> ref = EnsureInitialized.INSTANCE.get(defc); 381 if (ref == null) { 382 return true; // the final state 383 } 384 Thread clinitThread = ref.get(); 385 // Somebody may still be running defc.<clinit>. 386 if (clinitThread == Thread.currentThread()) { 387 // If anybody is running defc.<clinit>, it is this thread. 388 if (UNSAFE.shouldBeInitialized(defc)) 389 // Yes, we are running it; keep the barrier for now. 390 return false; 391 } else { 392 // We are in a random thread. Block. 393 UNSAFE.ensureClassInitialized(defc); 394 } 395 assert(!UNSAFE.shouldBeInitialized(defc)); 396 // put it into the final state 397 EnsureInitialized.INSTANCE.remove(defc); 398 return true; 399 } 400 401 /*non-public*/ ensureInitialized(Object mh)402 static void ensureInitialized(Object mh) { 403 ((DirectMethodHandle)mh).ensureInitialized(); 404 } 405 406 /** This subclass represents invokespecial instructions. */ 407 static class Special extends DirectMethodHandle { 408 private final Class<?> caller; Special(MethodType mtype, LambdaForm form, MemberName member, Class<?> caller)409 private Special(MethodType mtype, LambdaForm form, MemberName member, Class<?> caller) { 410 super(mtype, form, member); 411 this.caller = caller; 412 } 413 @Override isInvokeSpecial()414 boolean isInvokeSpecial() { 415 return true; 416 } 417 @Override copyWith(MethodType mt, LambdaForm lf)418 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 419 return new Special(mt, lf, member, caller); 420 } checkReceiver(Object recv)421 Object checkReceiver(Object recv) { 422 if (!caller.isInstance(recv)) { 423 String msg = String.format("Receiver class %s is not a subclass of caller class %s", 424 recv.getClass().getName(), caller.getName()); 425 throw new IncompatibleClassChangeError(msg); 426 } 427 return recv; 428 } 429 } 430 431 /** This subclass represents invokeinterface instructions. */ 432 static class Interface extends DirectMethodHandle { 433 private final Class<?> refc; Interface(MethodType mtype, LambdaForm form, MemberName member, Class<?> refc)434 private Interface(MethodType mtype, LambdaForm form, MemberName member, Class<?> refc) { 435 super(mtype, form, member); 436 assert refc.isInterface() : refc; 437 this.refc = refc; 438 } 439 @Override copyWith(MethodType mt, LambdaForm lf)440 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 441 return new Interface(mt, lf, member, refc); 442 } 443 @Override checkReceiver(Object recv)444 Object checkReceiver(Object recv) { 445 if (!refc.isInstance(recv)) { 446 String msg = String.format("Receiver class %s does not implement the requested interface %s", 447 recv.getClass().getName(), refc.getName()); 448 throw new IncompatibleClassChangeError(msg); 449 } 450 return recv; 451 } 452 } 453 454 /** Used for interface receiver type checks, by Interface and Special modes. */ checkReceiver(Object recv)455 Object checkReceiver(Object recv) { 456 throw new InternalError("Should only be invoked on a subclass"); 457 } 458 459 460 /** This subclass handles constructor references. */ 461 static class Constructor extends DirectMethodHandle { 462 final MemberName initMethod; 463 final Class<?> instanceClass; 464 Constructor(MethodType mtype, LambdaForm form, MemberName constructor, MemberName initMethod, Class<?> instanceClass)465 private Constructor(MethodType mtype, LambdaForm form, MemberName constructor, 466 MemberName initMethod, Class<?> instanceClass) { 467 super(mtype, form, constructor); 468 this.initMethod = initMethod; 469 this.instanceClass = instanceClass; 470 assert(initMethod.isResolved()); 471 } 472 @Override copyWith(MethodType mt, LambdaForm lf)473 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 474 return new Constructor(mt, lf, member, initMethod, instanceClass); 475 } 476 } 477 478 /*non-public*/ constructorMethod(Object mh)479 static Object constructorMethod(Object mh) { 480 Constructor dmh = (Constructor)mh; 481 return dmh.initMethod; 482 } 483 484 /*non-public*/ allocateInstance(Object mh)485 static Object allocateInstance(Object mh) throws InstantiationException { 486 Constructor dmh = (Constructor)mh; 487 return UNSAFE.allocateInstance(dmh.instanceClass); 488 } 489 490 /** This subclass handles non-static field references. */ 491 static class Accessor extends DirectMethodHandle { 492 final Class<?> fieldType; 493 final int fieldOffset; Accessor(MethodType mtype, LambdaForm form, MemberName member, int fieldOffset)494 private Accessor(MethodType mtype, LambdaForm form, MemberName member, 495 int fieldOffset) { 496 super(mtype, form, member); 497 this.fieldType = member.getFieldType(); 498 this.fieldOffset = fieldOffset; 499 } 500 checkCast(Object obj)501 @Override Object checkCast(Object obj) { 502 return fieldType.cast(obj); 503 } 504 @Override copyWith(MethodType mt, LambdaForm lf)505 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 506 return new Accessor(mt, lf, member, fieldOffset); 507 } 508 } 509 510 @ForceInline 511 /*non-public*/ fieldOffset(Object accessorObj)512 static long fieldOffset(Object accessorObj) { 513 // Note: We return a long because that is what Unsafe.getObject likes. 514 // We store a plain int because it is more compact. 515 return ((Accessor)accessorObj).fieldOffset; 516 } 517 518 @ForceInline 519 /*non-public*/ checkBase(Object obj)520 static Object checkBase(Object obj) { 521 // Note that the object's class has already been verified, 522 // since the parameter type of the Accessor method handle 523 // is either member.getDeclaringClass or a subclass. 524 // This was verified in DirectMethodHandle.make. 525 // Therefore, the only remaining check is for null. 526 // Since this check is *not* guaranteed by Unsafe.getInt 527 // and its siblings, we need to make an explicit one here. 528 return Objects.requireNonNull(obj); 529 } 530 531 /** This subclass handles static field references. */ 532 static class StaticAccessor extends DirectMethodHandle { 533 private final Class<?> fieldType; 534 private final Object staticBase; 535 private final long staticOffset; 536 StaticAccessor(MethodType mtype, LambdaForm form, MemberName member, Object staticBase, long staticOffset)537 private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member, 538 Object staticBase, long staticOffset) { 539 super(mtype, form, member); 540 this.fieldType = member.getFieldType(); 541 this.staticBase = staticBase; 542 this.staticOffset = staticOffset; 543 } 544 checkCast(Object obj)545 @Override Object checkCast(Object obj) { 546 return fieldType.cast(obj); 547 } 548 @Override copyWith(MethodType mt, LambdaForm lf)549 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 550 return new StaticAccessor(mt, lf, member, staticBase, staticOffset); 551 } 552 } 553 554 @ForceInline 555 /*non-public*/ nullCheck(Object obj)556 static Object nullCheck(Object obj) { 557 return Objects.requireNonNull(obj); 558 } 559 560 @ForceInline 561 /*non-public*/ staticBase(Object accessorObj)562 static Object staticBase(Object accessorObj) { 563 return ((StaticAccessor)accessorObj).staticBase; 564 } 565 566 @ForceInline 567 /*non-public*/ staticOffset(Object accessorObj)568 static long staticOffset(Object accessorObj) { 569 return ((StaticAccessor)accessorObj).staticOffset; 570 } 571 572 @ForceInline 573 /*non-public*/ checkCast(Object mh, Object obj)574 static Object checkCast(Object mh, Object obj) { 575 return ((DirectMethodHandle) mh).checkCast(obj); 576 } 577 checkCast(Object obj)578 Object checkCast(Object obj) { 579 return member.getReturnType().cast(obj); 580 } 581 582 // Caching machinery for field accessors: 583 static final byte 584 AF_GETFIELD = 0, 585 AF_PUTFIELD = 1, 586 AF_GETSTATIC = 2, 587 AF_PUTSTATIC = 3, 588 AF_GETSTATIC_INIT = 4, 589 AF_PUTSTATIC_INIT = 5, 590 AF_LIMIT = 6; 591 // Enumerate the different field kinds using Wrapper, 592 // with an extra case added for checked references. 593 static final int 594 FT_LAST_WRAPPER = Wrapper.COUNT-1, 595 FT_UNCHECKED_REF = Wrapper.OBJECT.ordinal(), 596 FT_CHECKED_REF = FT_LAST_WRAPPER+1, 597 FT_LIMIT = FT_LAST_WRAPPER+2; afIndex(byte formOp, boolean isVolatile, int ftypeKind)598 private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) { 599 return ((formOp * FT_LIMIT * 2) 600 + (isVolatile ? FT_LIMIT : 0) 601 + ftypeKind); 602 } 603 @Stable 604 private static final LambdaForm[] ACCESSOR_FORMS 605 = new LambdaForm[afIndex(AF_LIMIT, false, 0)]; ftypeKind(Class<?> ftype)606 static int ftypeKind(Class<?> ftype) { 607 if (ftype.isPrimitive()) 608 return Wrapper.forPrimitiveType(ftype).ordinal(); 609 else if (VerifyType.isNullReferenceConversion(Object.class, ftype)) 610 return FT_UNCHECKED_REF; 611 else 612 return FT_CHECKED_REF; 613 } 614 615 /** 616 * Create a LF which can access the given field. 617 * Cache and share this structure among all fields with 618 * the same basicType and refKind. 619 */ preparedFieldLambdaForm(MemberName m)620 private static LambdaForm preparedFieldLambdaForm(MemberName m) { 621 Class<?> ftype = m.getFieldType(); 622 boolean isVolatile = m.isVolatile(); 623 byte formOp; 624 switch (m.getReferenceKind()) { 625 case REF_getField: formOp = AF_GETFIELD; break; 626 case REF_putField: formOp = AF_PUTFIELD; break; 627 case REF_getStatic: formOp = AF_GETSTATIC; break; 628 case REF_putStatic: formOp = AF_PUTSTATIC; break; 629 default: throw new InternalError(m.toString()); 630 } 631 if (shouldBeInitialized(m)) { 632 // precompute the barrier-free version: 633 preparedFieldLambdaForm(formOp, isVolatile, ftype); 634 assert((AF_GETSTATIC_INIT - AF_GETSTATIC) == 635 (AF_PUTSTATIC_INIT - AF_PUTSTATIC)); 636 formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC); 637 } 638 LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype); 639 maybeCompile(lform, m); 640 assert(lform.methodType().dropParameterTypes(0, 1) 641 .equals(m.getInvocationType().basicType())) 642 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 643 return lform; 644 } preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype)645 private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) { 646 int ftypeKind = ftypeKind(ftype); 647 int afIndex = afIndex(formOp, isVolatile, ftypeKind); 648 LambdaForm lform = ACCESSOR_FORMS[afIndex]; 649 if (lform != null) return lform; 650 lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind); 651 ACCESSOR_FORMS[afIndex] = lform; // don't bother with a CAS 652 return lform; 653 } 654 655 private static final Wrapper[] ALL_WRAPPERS = Wrapper.values(); 656 getFieldKind(boolean isGetter, boolean isVolatile, Wrapper wrapper)657 private static Kind getFieldKind(boolean isGetter, boolean isVolatile, Wrapper wrapper) { 658 if (isGetter) { 659 if (isVolatile) { 660 switch (wrapper) { 661 case BOOLEAN: return GET_BOOLEAN_VOLATILE; 662 case BYTE: return GET_BYTE_VOLATILE; 663 case SHORT: return GET_SHORT_VOLATILE; 664 case CHAR: return GET_CHAR_VOLATILE; 665 case INT: return GET_INT_VOLATILE; 666 case LONG: return GET_LONG_VOLATILE; 667 case FLOAT: return GET_FLOAT_VOLATILE; 668 case DOUBLE: return GET_DOUBLE_VOLATILE; 669 case OBJECT: return GET_REFERENCE_VOLATILE; 670 } 671 } else { 672 switch (wrapper) { 673 case BOOLEAN: return GET_BOOLEAN; 674 case BYTE: return GET_BYTE; 675 case SHORT: return GET_SHORT; 676 case CHAR: return GET_CHAR; 677 case INT: return GET_INT; 678 case LONG: return GET_LONG; 679 case FLOAT: return GET_FLOAT; 680 case DOUBLE: return GET_DOUBLE; 681 case OBJECT: return GET_REFERENCE; 682 } 683 } 684 } else { 685 if (isVolatile) { 686 switch (wrapper) { 687 case BOOLEAN: return PUT_BOOLEAN_VOLATILE; 688 case BYTE: return PUT_BYTE_VOLATILE; 689 case SHORT: return PUT_SHORT_VOLATILE; 690 case CHAR: return PUT_CHAR_VOLATILE; 691 case INT: return PUT_INT_VOLATILE; 692 case LONG: return PUT_LONG_VOLATILE; 693 case FLOAT: return PUT_FLOAT_VOLATILE; 694 case DOUBLE: return PUT_DOUBLE_VOLATILE; 695 case OBJECT: return PUT_REFERENCE_VOLATILE; 696 } 697 } else { 698 switch (wrapper) { 699 case BOOLEAN: return PUT_BOOLEAN; 700 case BYTE: return PUT_BYTE; 701 case SHORT: return PUT_SHORT; 702 case CHAR: return PUT_CHAR; 703 case INT: return PUT_INT; 704 case LONG: return PUT_LONG; 705 case FLOAT: return PUT_FLOAT; 706 case DOUBLE: return PUT_DOUBLE; 707 case OBJECT: return PUT_REFERENCE; 708 } 709 } 710 } 711 throw new AssertionError("Invalid arguments"); 712 } 713 makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind)714 static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) { 715 boolean isGetter = (formOp & 1) == (AF_GETFIELD & 1); 716 boolean isStatic = (formOp >= AF_GETSTATIC); 717 boolean needsInit = (formOp >= AF_GETSTATIC_INIT); 718 boolean needsCast = (ftypeKind == FT_CHECKED_REF); 719 Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]); 720 Class<?> ft = fw.primitiveType(); 721 assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind); 722 723 // getObject, putIntVolatile, etc. 724 Kind kind = getFieldKind(isGetter, isVolatile, fw); 725 726 MethodType linkerType; 727 if (isGetter) 728 linkerType = MethodType.methodType(ft, Object.class, long.class); 729 else 730 linkerType = MethodType.methodType(void.class, Object.class, long.class, ft); 731 MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual); 732 try { 733 linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class); 734 } catch (ReflectiveOperationException ex) { 735 throw newInternalError(ex); 736 } 737 738 // What is the external type of the lambda form? 739 MethodType mtype; 740 if (isGetter) 741 mtype = MethodType.methodType(ft); 742 else 743 mtype = MethodType.methodType(void.class, ft); 744 mtype = mtype.basicType(); // erase short to int, etc. 745 if (!isStatic) 746 mtype = mtype.insertParameterTypes(0, Object.class); 747 final int DMH_THIS = 0; 748 final int ARG_BASE = 1; 749 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 750 // if this is for non-static access, the base pointer is stored at this index: 751 final int OBJ_BASE = isStatic ? -1 : ARG_BASE; 752 // if this is for write access, the value to be written is stored at this index: 753 final int SET_VALUE = isGetter ? -1 : ARG_LIMIT - 1; 754 int nameCursor = ARG_LIMIT; 755 final int F_HOLDER = (isStatic ? nameCursor++ : -1); // static base if any 756 final int F_OFFSET = nameCursor++; // Either static offset or field offset. 757 final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1); 758 final int U_HOLDER = nameCursor++; // UNSAFE holder 759 final int INIT_BAR = (needsInit ? nameCursor++ : -1); 760 final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1); 761 final int LINKER_CALL = nameCursor++; 762 final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1); 763 final int RESULT = nameCursor-1; // either the call or the cast 764 Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); 765 if (needsInit) 766 names[INIT_BAR] = new Name(getFunction(NF_ensureInitialized), names[DMH_THIS]); 767 if (needsCast && !isGetter) 768 names[PRE_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[SET_VALUE]); 769 Object[] outArgs = new Object[1 + linkerType.parameterCount()]; 770 assert(outArgs.length == (isGetter ? 3 : 4)); 771 outArgs[0] = names[U_HOLDER] = new Name(getFunction(NF_UNSAFE)); 772 if (isStatic) { 773 outArgs[1] = names[F_HOLDER] = new Name(getFunction(NF_staticBase), names[DMH_THIS]); 774 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_staticOffset), names[DMH_THIS]); 775 } else { 776 outArgs[1] = names[OBJ_CHECK] = new Name(getFunction(NF_checkBase), names[OBJ_BASE]); 777 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_fieldOffset), names[DMH_THIS]); 778 } 779 if (!isGetter) { 780 outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]); 781 } 782 for (Object a : outArgs) assert(a != null); 783 names[LINKER_CALL] = new Name(linker, outArgs); 784 if (needsCast && isGetter) 785 names[POST_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[LINKER_CALL]); 786 for (Name n : names) assert(n != null); 787 788 LambdaForm form; 789 if (needsCast || needsInit) { 790 // can't use the pre-generated form when casting and/or initializing 791 form = new LambdaForm(ARG_LIMIT, names, RESULT); 792 } else { 793 form = new LambdaForm(ARG_LIMIT, names, RESULT, kind); 794 } 795 796 if (LambdaForm.debugNames()) { 797 // add some detail to the lambdaForm debugname, 798 // significant only for debugging 799 StringBuilder nameBuilder = new StringBuilder(kind.methodName); 800 if (isStatic) { 801 nameBuilder.append("Static"); 802 } else { 803 nameBuilder.append("Field"); 804 } 805 if (needsCast) { 806 nameBuilder.append("Cast"); 807 } 808 if (needsInit) { 809 nameBuilder.append("Init"); 810 } 811 LambdaForm.associateWithDebugName(form, nameBuilder.toString()); 812 } 813 return form; 814 } 815 816 /** 817 * Pre-initialized NamedFunctions for bootstrapping purposes. 818 */ 819 static final byte NF_internalMemberName = 0, 820 NF_internalMemberNameEnsureInit = 1, 821 NF_ensureInitialized = 2, 822 NF_fieldOffset = 3, 823 NF_checkBase = 4, 824 NF_staticBase = 5, 825 NF_staticOffset = 6, 826 NF_checkCast = 7, 827 NF_allocateInstance = 8, 828 NF_constructorMethod = 9, 829 NF_UNSAFE = 10, 830 NF_checkReceiver = 11, 831 NF_LIMIT = 12; 832 833 private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT]; 834 getFunction(byte func)835 private static NamedFunction getFunction(byte func) { 836 NamedFunction nf = NFS[func]; 837 if (nf != null) { 838 return nf; 839 } 840 // Each nf must be statically invocable or we get tied up in our bootstraps. 841 nf = NFS[func] = createFunction(func); 842 assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf)); 843 return nf; 844 } 845 846 private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class); 847 848 private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class); 849 createFunction(byte func)850 private static NamedFunction createFunction(byte func) { 851 try { 852 switch (func) { 853 case NF_internalMemberName: 854 return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE); 855 case NF_internalMemberNameEnsureInit: 856 return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE); 857 case NF_ensureInitialized: 858 return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class)); 859 case NF_fieldOffset: 860 return getNamedFunction("fieldOffset", LONG_OBJ_TYPE); 861 case NF_checkBase: 862 return getNamedFunction("checkBase", OBJ_OBJ_TYPE); 863 case NF_staticBase: 864 return getNamedFunction("staticBase", OBJ_OBJ_TYPE); 865 case NF_staticOffset: 866 return getNamedFunction("staticOffset", LONG_OBJ_TYPE); 867 case NF_checkCast: 868 return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class)); 869 case NF_allocateInstance: 870 return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE); 871 case NF_constructorMethod: 872 return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE); 873 case NF_UNSAFE: 874 MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getField); 875 return new NamedFunction( 876 MemberName.getFactory() 877 .resolveOrFail(REF_getField, member, DirectMethodHandle.class, NoSuchMethodException.class)); 878 case NF_checkReceiver: 879 member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual); 880 return new NamedFunction( 881 MemberName.getFactory() 882 .resolveOrFail(REF_invokeVirtual, member, DirectMethodHandle.class, NoSuchMethodException.class)); 883 default: 884 throw newInternalError("Unknown function: " + func); 885 } 886 } catch (ReflectiveOperationException ex) { 887 throw newInternalError(ex); 888 } 889 } 890 getNamedFunction(String name, MethodType type)891 private static NamedFunction getNamedFunction(String name, MethodType type) 892 throws ReflectiveOperationException 893 { 894 MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic); 895 return new NamedFunction( 896 MemberName.getFactory() 897 .resolveOrFail(REF_invokeStatic, member, DirectMethodHandle.class, NoSuchMethodException.class)); 898 } 899 900 static { 901 // The Holder class will contain pre-generated DirectMethodHandles resolved 902 // speculatively using MemberName.getFactory().resolveOrNull. However, that 903 // doesn't initialize the class, which subtly breaks inlining etc. By forcing 904 // initialization of the Holder class we avoid these issues. 905 UNSAFE.ensureClassInitialized(Holder.class); 906 } 907 908 /* Placeholder class for DirectMethodHandles generated ahead of time */ 909 final class Holder {} 910 } 911