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