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