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