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()) { 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 boolean checkInitialized() { 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 boolean initializingStill = UNSAFE.shouldBeInitialized(defc); 395 if (initializingStill && member.isStrict()) { 396 // while <clinit> is running, we track access to strict static fields 397 UNSAFE.notifyStrictStaticAccess(defc, staticOffset(this), member.isSetter()); 398 } 399 return !initializingStill; 400 } 401 402 /*non-public*/ 403 static void ensureInitialized(Object mh) { 404 ((DirectMethodHandle)mh).ensureInitialized(); 405 } 406 407 /** This subclass represents invokespecial instructions. */ 408 static final class Special extends DirectMethodHandle { 409 private final Class<?> caller; 410 private Special(MethodType mtype, LambdaForm form, MemberName member, boolean crackable, Class<?> caller) { 411 super(mtype, form, member, crackable); 412 this.caller = caller; 413 } 414 @Override 415 boolean isInvokeSpecial() { 416 return true; 417 } 418 @Override 419 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 420 return new Special(mt, lf, member, crackable, caller); 421 } 422 @Override 423 MethodHandle viewAsType(MethodType newType, boolean strict) { 424 assert(viewAsTypeChecks(newType, strict)); 425 return new Special(newType, form, member, false, caller); 426 } 427 Object checkReceiver(Object recv) { 428 if (!caller.isInstance(recv)) { 429 if (recv != null) { 430 String msg = String.format("Receiver class %s is not a subclass of caller class %s", 431 recv.getClass().getName(), caller.getName()); 432 throw new IncompatibleClassChangeError(msg); 433 } else { 434 String msg = String.format("Cannot invoke %s with null receiver", member); 435 throw new NullPointerException(msg); 436 } 437 } 438 return recv; 439 } 440 } 441 442 /** This subclass represents invokeinterface instructions. */ 443 static final class Interface extends DirectMethodHandle { 444 private final Class<?> refc; 445 private Interface(MethodType mtype, LambdaForm form, MemberName member, boolean crackable, Class<?> refc) { 446 super(mtype, form, member, crackable); 447 assert(refc.isInterface()) : refc; 448 this.refc = refc; 449 } 450 @Override 451 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 452 return new Interface(mt, lf, member, crackable, refc); 453 } 454 @Override 455 MethodHandle viewAsType(MethodType newType, boolean strict) { 456 assert(viewAsTypeChecks(newType, strict)); 457 return new Interface(newType, form, member, false, refc); 458 } 459 @Override 460 Object checkReceiver(Object recv) { 461 if (!refc.isInstance(recv)) { 462 if (recv != null) { 463 String msg = String.format("Receiver class %s does not implement the requested interface %s", 464 recv.getClass().getName(), refc.getName()); 465 throw new IncompatibleClassChangeError(msg); 466 } else { 467 String msg = String.format("Cannot invoke %s with null receiver", member); 468 throw new NullPointerException(msg); 469 } 470 } 471 return recv; 472 } 473 } 474 475 /** Used for interface receiver type checks, by Interface and Special modes. */ 476 Object checkReceiver(Object recv) { 477 throw new InternalError("Should only be invoked on a subclass"); 478 } 479 480 /** This subclass handles constructor references. */ 481 static final class Constructor extends DirectMethodHandle { 482 final MemberName initMethod; 483 final Class<?> instanceClass; 484 485 private Constructor(MethodType mtype, LambdaForm form, MemberName constructor, 486 boolean crackable, MemberName initMethod, Class<?> instanceClass) { 487 super(mtype, form, constructor, crackable); 488 this.initMethod = initMethod; 489 this.instanceClass = instanceClass; 490 assert(initMethod.isResolved()); 491 } 492 @Override 493 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 494 return new Constructor(mt, lf, member, crackable, initMethod, instanceClass); 495 } 496 @Override 497 MethodHandle viewAsType(MethodType newType, boolean strict) { 498 assert(viewAsTypeChecks(newType, strict)); 499 return new Constructor(newType, form, member, false, initMethod, instanceClass); 500 } 501 } 502 503 /*non-public*/ 504 static Object constructorMethod(Object mh) { 505 Constructor dmh = (Constructor)mh; 506 return dmh.initMethod; 507 } 508 509 /*non-public*/ 510 static Object allocateInstance(Object mh) throws InstantiationException { 511 Constructor dmh = (Constructor)mh; 512 return UNSAFE.allocateInstance(dmh.instanceClass); 513 } 514 515 /** This subclass handles non-static field references. */ 516 static final class Accessor extends DirectMethodHandle { 517 final Class<?> fieldType; 518 final int fieldOffset; 519 final int layout; 520 private Accessor(MethodType mtype, LambdaForm form, MemberName member, 521 boolean crackable, int fieldOffset) { 522 super(mtype, form, member, crackable); 523 this.fieldType = member.getFieldType(); 524 this.fieldOffset = fieldOffset; 525 this.layout = member.getLayout(); 526 } 527 528 @Override Object checkCast(Object obj) { 529 return fieldType.cast(obj); 530 } 531 @Override 532 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 533 return new Accessor(mt, lf, member, crackable, fieldOffset); 534 } 535 @Override 536 MethodHandle viewAsType(MethodType newType, boolean strict) { 537 assert(viewAsTypeChecks(newType, strict)); 538 return new Accessor(newType, form, member, false, fieldOffset); 539 } 540 } 541 542 @ForceInline 543 /*non-public*/ 544 static long fieldOffset(Object accessorObj) { 545 // Note: We return a long because that is what Unsafe.getObject likes. 546 // We store a plain int because it is more compact. 547 return ((Accessor)accessorObj).fieldOffset; 548 } 549 550 @ForceInline 551 /*non-public*/ 552 static Object checkBase(Object obj) { 553 // Note that the object's class has already been verified, 554 // since the parameter type of the Accessor method handle 555 // is either member.getDeclaringClass or a subclass. 556 // This was verified in DirectMethodHandle.make. 557 // Therefore, the only remaining check is for null. 558 // Since this check is *not* guaranteed by Unsafe.getInt 559 // and its siblings, we need to make an explicit one here. 560 return Objects.requireNonNull(obj); 561 } 562 563 /** This subclass handles static field references. */ 564 static final class StaticAccessor extends DirectMethodHandle { 565 private final Class<?> fieldType; 566 private final Object staticBase; 567 private final long staticOffset; 568 569 private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member, 570 boolean crackable, Object staticBase, long staticOffset) { 571 super(mtype, form, member, crackable); 572 this.fieldType = member.getFieldType(); 573 this.staticBase = staticBase; 574 this.staticOffset = staticOffset; 575 } 576 577 @Override Object checkCast(Object obj) { 578 return fieldType.cast(obj); 579 } 580 @Override 581 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 582 return new StaticAccessor(mt, lf, member, crackable, staticBase, staticOffset); 583 } 584 @Override 585 MethodHandle viewAsType(MethodType newType, boolean strict) { 586 assert(viewAsTypeChecks(newType, strict)); 587 return new StaticAccessor(newType, form, member, false, staticBase, staticOffset); 588 } 589 } 590 591 @ForceInline 592 /*non-public*/ 593 static Object nullCheck(Object obj) { 594 return Objects.requireNonNull(obj); 595 } 596 597 @ForceInline 598 /*non-public*/ 599 static Object staticBase(Object accessorObj) { 600 return ((StaticAccessor)accessorObj).staticBase; 601 } 602 603 @ForceInline 604 /*non-public*/ 605 static long staticOffset(Object accessorObj) { 606 return ((StaticAccessor)accessorObj).staticOffset; 607 } 608 609 @ForceInline 610 /*non-public*/ 611 static Object checkCast(Object mh, Object obj) { 612 return ((DirectMethodHandle) mh).checkCast(obj); 613 } 614 615 @ForceInline 616 /*non-public*/ static Class<?> fieldType(Object accessorObj) { 617 return ((Accessor) accessorObj).fieldType; 618 } 619 620 @ForceInline 621 static int fieldLayout(Object accessorObj) { 622 return ((Accessor) accessorObj).layout; 623 } 624 625 @ForceInline 626 /*non-public*/ static Class<?> staticFieldType(Object accessorObj) { 627 return ((StaticAccessor) accessorObj).fieldType; 628 } 629 630 Object checkCast(Object obj) { 631 return member.getMethodType().returnType().cast(obj); 632 } 633 634 // Caching machinery for field accessors: 635 static final byte 636 AF_GETFIELD = 0, 637 AF_PUTFIELD = 1, 638 AF_GETSTATIC = 2, 639 AF_PUTSTATIC = 3, 640 AF_GETSTATIC_INIT = 4, 641 AF_PUTSTATIC_INIT = 5, 642 AF_LIMIT = 6; 643 // Enumerate the different field kinds using Wrapper, 644 // with an extra case added for checked references and value field access 645 static final int 646 FT_LAST_WRAPPER = Wrapper.COUNT-1, 647 FT_UNCHECKED_REF = Wrapper.OBJECT.ordinal(), 648 FT_CHECKED_REF = FT_LAST_WRAPPER+1, 649 FT_CHECKED_VALUE = FT_LAST_WRAPPER+2, // flat vs non-flat x null value vs null-restricted value 650 FT_LIMIT = FT_LAST_WRAPPER+6; 651 private static int afIndex(byte formOp, boolean isVolatile, boolean isFlat, boolean isNullRestricted, int ftypeKind) { 652 return ((formOp * FT_LIMIT * 2) 653 + (isVolatile ? FT_LIMIT : 0) 654 + (isFlat ? 1 : 0) 655 + (isNullRestricted ? 1 : 0) 656 + ftypeKind); 657 } 658 @Stable 659 private static final LambdaForm[] ACCESSOR_FORMS 660 = new LambdaForm[afIndex(AF_LIMIT, false, false, false, 0)]; 661 static int ftypeKind(Class<?> ftype) { 662 if (ftype.isPrimitive()) { 663 return Wrapper.forPrimitiveType(ftype).ordinal(); 664 } else if (ftype.isInterface() || ftype.isAssignableFrom(Object.class)) { 665 // retyping can be done without a cast 666 return FT_UNCHECKED_REF; 667 } else { 668 return ftype.isValue() ? FT_CHECKED_VALUE : FT_CHECKED_REF; 669 } 670 } 671 672 /** 673 * Create a LF which can access the given field. 674 * Cache and share this structure among all fields with 675 * the same basicType and refKind. 676 */ 677 private static LambdaForm preparedFieldLambdaForm(MemberName m) { 678 Class<?> ftype = m.getFieldType(); 679 byte formOp = switch (m.getReferenceKind()) { 680 case REF_getField -> AF_GETFIELD; 681 case REF_putField -> AF_PUTFIELD; 682 case REF_getStatic -> AF_GETSTATIC; 683 case REF_putStatic -> AF_PUTSTATIC; 684 default -> throw new InternalError(m.toString()); 685 }; 686 if (shouldBeInitialized(m)) { 687 // precompute the barrier-free version: 688 preparedFieldLambdaForm(formOp, m.isVolatile(), m.isFlat(), m.isNullRestricted(), ftype); 689 assert((AF_GETSTATIC_INIT - AF_GETSTATIC) == 690 (AF_PUTSTATIC_INIT - AF_PUTSTATIC)); 691 formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC); 692 } 693 LambdaForm lform = preparedFieldLambdaForm(formOp, m.isVolatile(), m.isFlat(), m.isNullRestricted(), ftype); 694 maybeCompile(lform, m); 695 assert(lform.methodType().dropParameterTypes(0, 1) 696 .equals(m.getInvocationType().basicType())) 697 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 698 return lform; 699 } 700 701 private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, 702 boolean isFlat, boolean isNullRestricted, Class<?> ftype) { 703 int ftypeKind = ftypeKind(ftype); 704 int afIndex = afIndex(formOp, isVolatile, isFlat, isNullRestricted, ftypeKind); 705 LambdaForm lform = ACCESSOR_FORMS[afIndex]; 706 if (lform != null) return lform; 707 lform = makePreparedFieldLambdaForm(formOp, isVolatile,isFlat, isNullRestricted, ftypeKind); 708 ACCESSOR_FORMS[afIndex] = lform; // don't bother with a CAS 709 return lform; 710 } 711 712 private static final Wrapper[] ALL_WRAPPERS = Wrapper.values(); 713 714 private static Kind getFieldKind(boolean isGetter, boolean isVolatile, boolean isFlat, Wrapper wrapper) { 715 if (isGetter) { 716 if (isVolatile) { 717 switch (wrapper) { 718 case BOOLEAN: return GET_BOOLEAN_VOLATILE; 719 case BYTE: return GET_BYTE_VOLATILE; 720 case SHORT: return GET_SHORT_VOLATILE; 721 case CHAR: return GET_CHAR_VOLATILE; 722 case INT: return GET_INT_VOLATILE; 723 case LONG: return GET_LONG_VOLATILE; 724 case FLOAT: return GET_FLOAT_VOLATILE; 725 case DOUBLE: return GET_DOUBLE_VOLATILE; 726 case OBJECT: return isFlat ? GET_FLAT_VALUE_VOLATILE : GET_REFERENCE_VOLATILE; 727 } 728 } else { 729 switch (wrapper) { 730 case BOOLEAN: return GET_BOOLEAN; 731 case BYTE: return GET_BYTE; 732 case SHORT: return GET_SHORT; 733 case CHAR: return GET_CHAR; 734 case INT: return GET_INT; 735 case LONG: return GET_LONG; 736 case FLOAT: return GET_FLOAT; 737 case DOUBLE: return GET_DOUBLE; 738 case OBJECT: return isFlat ? GET_FLAT_VALUE : GET_REFERENCE; 739 } 740 } 741 } else { 742 if (isVolatile) { 743 switch (wrapper) { 744 case BOOLEAN: return PUT_BOOLEAN_VOLATILE; 745 case BYTE: return PUT_BYTE_VOLATILE; 746 case SHORT: return PUT_SHORT_VOLATILE; 747 case CHAR: return PUT_CHAR_VOLATILE; 748 case INT: return PUT_INT_VOLATILE; 749 case LONG: return PUT_LONG_VOLATILE; 750 case FLOAT: return PUT_FLOAT_VOLATILE; 751 case DOUBLE: return PUT_DOUBLE_VOLATILE; 752 case OBJECT: return isFlat ? PUT_FLAT_VALUE_VOLATILE : PUT_REFERENCE_VOLATILE; 753 } 754 } else { 755 switch (wrapper) { 756 case BOOLEAN: return PUT_BOOLEAN; 757 case BYTE: return PUT_BYTE; 758 case SHORT: return PUT_SHORT; 759 case CHAR: return PUT_CHAR; 760 case INT: return PUT_INT; 761 case LONG: return PUT_LONG; 762 case FLOAT: return PUT_FLOAT; 763 case DOUBLE: return PUT_DOUBLE; 764 case OBJECT: return isFlat ? PUT_FLAT_VALUE : PUT_REFERENCE; 765 } 766 } 767 } 768 throw new AssertionError("Invalid arguments"); 769 } 770 771 /** invoked by GenerateJLIClassesHelper */ 772 static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftype) { 773 return makePreparedFieldLambdaForm(formOp, isVolatile, false, false, ftype); 774 } 775 776 private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, 777 boolean isFlat, boolean isNullRestricted, int ftypeKind) { 778 boolean isGetter = (formOp & 1) == (AF_GETFIELD & 1); 779 boolean isStatic = (formOp >= AF_GETSTATIC); 780 boolean needsInit = (formOp >= AF_GETSTATIC_INIT); 781 boolean needsCast = (ftypeKind == FT_CHECKED_REF || ftypeKind == FT_CHECKED_VALUE); 782 Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]); 783 Class<?> ft = fw.primitiveType(); 784 assert(needsCast ? true : ftypeKind(ft) == ftypeKind); 785 786 // getObject, putIntVolatile, etc. 787 Kind kind = getFieldKind(isGetter, isVolatile, isFlat, fw); 788 789 MethodType linkerType; 790 if (isGetter) { 791 linkerType = isFlat 792 ? MethodType.methodType(ft, Object.class, long.class, int.class, Class.class) 793 : MethodType.methodType(ft, Object.class, long.class); 794 } else { 795 linkerType = isFlat 796 ? MethodType.methodType(void.class, Object.class, long.class, int.class, Class.class, ft) 797 : MethodType.methodType(void.class, Object.class, long.class, ft); 798 } 799 MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual); 800 try { 801 linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, LM_TRUSTED, 802 NoSuchMethodException.class); 803 } catch (ReflectiveOperationException ex) { 804 throw newInternalError(ex); 805 } 806 807 // What is the external type of the lambda form? 808 MethodType mtype; 809 if (isGetter) 810 mtype = MethodType.methodType(ft); 811 else 812 mtype = MethodType.methodType(void.class, ft); 813 mtype = mtype.basicType(); // erase short to int, etc. 814 if (!isStatic) 815 mtype = mtype.insertParameterTypes(0, Object.class); 816 final int DMH_THIS = 0; 817 final int ARG_BASE = 1; 818 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 819 // if this is for non-static access, the base pointer is stored at this index: 820 final int OBJ_BASE = isStatic ? -1 : ARG_BASE; 821 // if this is for write access, the value to be written is stored at this index: 822 final int SET_VALUE = isGetter ? -1 : ARG_LIMIT - 1; 823 int nameCursor = ARG_LIMIT; 824 final int F_HOLDER = (isStatic ? nameCursor++ : -1); // static base if any 825 final int F_OFFSET = nameCursor++; // Either static offset or field offset. 826 final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1); 827 final int U_HOLDER = nameCursor++; // UNSAFE holder 828 final int INIT_BAR = (needsInit ? nameCursor++ : -1); 829 final int LAYOUT = (isFlat ? nameCursor++ : -1); // field must be instance 830 final int VALUE_TYPE = (isFlat ? nameCursor++ : -1); 831 final int NULL_CHECK = (isNullRestricted && !isGetter ? nameCursor++ : -1); 832 final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1); 833 final int LINKER_CALL = nameCursor++; 834 final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1); 835 final int RESULT = nameCursor-1; // either the call, or the cast 836 Name[] names = invokeArguments(nameCursor - ARG_LIMIT, mtype); 837 if (needsInit) 838 names[INIT_BAR] = new Name(getFunction(NF_ensureInitialized), names[DMH_THIS]); 839 if (!isGetter) { 840 if (isNullRestricted) 841 names[NULL_CHECK] = new Name(getFunction(NF_nullCheck), names[SET_VALUE]); 842 if (needsCast) 843 names[PRE_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[SET_VALUE]); 844 } 845 Object[] outArgs = new Object[1 + linkerType.parameterCount()]; 846 assert (outArgs.length == (isGetter ? 3 : 4) + (isFlat ? 2 : 0)); 847 outArgs[0] = names[U_HOLDER] = new Name(getFunction(NF_UNSAFE)); 848 if (isStatic) { 849 outArgs[1] = names[F_HOLDER] = new Name(getFunction(NF_staticBase), names[DMH_THIS]); 850 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_staticOffset), names[DMH_THIS]); 851 } else { 852 outArgs[1] = names[OBJ_CHECK] = new Name(getFunction(NF_checkBase), names[OBJ_BASE]); 853 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_fieldOffset), names[DMH_THIS]); 854 } 855 int x = 3; 856 if (isFlat) { 857 assert !isStatic : "static field is flat form requested"; 858 outArgs[x++] = names[LAYOUT] = new Name(getFunction(NF_fieldLayout), names[DMH_THIS]); 859 outArgs[x++] = names[VALUE_TYPE] = isStatic ? new Name(getFunction(NF_staticFieldType), names[DMH_THIS]) 860 : new Name(getFunction(NF_fieldType), names[DMH_THIS]); 861 } 862 if (!isGetter) { 863 outArgs[x] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]); 864 } 865 for (Object a : outArgs) assert(a != null); 866 names[LINKER_CALL] = new Name(linker, outArgs); 867 if (needsCast && isGetter) 868 names[POST_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[LINKER_CALL]); 869 for (Name n : names) assert(n != null); 870 871 LambdaForm form; 872 if (needsCast || needsInit) { 873 // can't use the pre-generated form when casting and/or initializing 874 form = LambdaForm.create(ARG_LIMIT, names, RESULT); 875 } else { 876 form = LambdaForm.create(ARG_LIMIT, names, RESULT, kind); 877 } 878 879 if (LambdaForm.debugNames()) { 880 // add some detail to the lambdaForm debugname, 881 // significant only for debugging 882 StringBuilder nameBuilder = new StringBuilder(kind.methodName); 883 if (isStatic) { 884 nameBuilder.append("Static"); 885 } else { 886 nameBuilder.append("Field"); 887 } 888 if (needsCast) { 889 nameBuilder.append("Cast"); 890 } 891 if (needsInit) { 892 nameBuilder.append("Init"); 893 } 894 LambdaForm.associateWithDebugName(form, nameBuilder.toString()); 895 } 896 return form; 897 } 898 899 /** 900 * Pre-initialized NamedFunctions for bootstrapping purposes. 901 */ 902 static final byte NF_internalMemberName = 0, 903 NF_internalMemberNameEnsureInit = 1, 904 NF_ensureInitialized = 2, 905 NF_fieldOffset = 3, 906 NF_checkBase = 4, 907 NF_staticBase = 5, 908 NF_staticOffset = 6, 909 NF_checkCast = 7, 910 NF_allocateInstance = 8, 911 NF_constructorMethod = 9, 912 NF_UNSAFE = 10, 913 NF_checkReceiver = 11, 914 NF_fieldType = 12, 915 NF_staticFieldType = 13, 916 NF_fieldLayout = 14, 917 NF_nullCheck = 15, 918 NF_LIMIT = 16; 919 920 private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT]; 921 922 private static NamedFunction getFunction(byte func) { 923 NamedFunction nf = NFS[func]; 924 if (nf != null) { 925 return nf; 926 } 927 // Each nf must be statically invocable or we get tied up in our bootstraps. 928 nf = NFS[func] = createFunction(func); 929 assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf)); 930 return nf; 931 } 932 933 private static final MethodType CLS_OBJ_TYPE = MethodType.methodType(Class.class, Object.class); 934 private static final MethodType INT_OBJ_TYPE = MethodType.methodType(int.class, Object.class); 935 936 private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class); 937 938 private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class); 939 940 private static NamedFunction createFunction(byte func) { 941 try { 942 switch (func) { 943 case NF_internalMemberName: 944 return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE); 945 case NF_internalMemberNameEnsureInit: 946 return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE); 947 case NF_ensureInitialized: 948 return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class)); 949 case NF_fieldOffset: 950 return getNamedFunction("fieldOffset", LONG_OBJ_TYPE); 951 case NF_checkBase: 952 return getNamedFunction("checkBase", OBJ_OBJ_TYPE); 953 case NF_staticBase: 954 return getNamedFunction("staticBase", OBJ_OBJ_TYPE); 955 case NF_staticOffset: 956 return getNamedFunction("staticOffset", LONG_OBJ_TYPE); 957 case NF_checkCast: 958 return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class)); 959 case NF_allocateInstance: 960 return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE); 961 case NF_constructorMethod: 962 return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE); 963 case NF_UNSAFE: 964 MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getStatic); 965 return new NamedFunction( 966 MemberName.getFactory().resolveOrFail(REF_getStatic, member, 967 DirectMethodHandle.class, LM_TRUSTED, 968 NoSuchFieldException.class)); 969 case NF_checkReceiver: 970 member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual); 971 return new NamedFunction( 972 MemberName.getFactory().resolveOrFail(REF_invokeVirtual, member, 973 DirectMethodHandle.class, LM_TRUSTED, 974 NoSuchMethodException.class)); 975 case NF_fieldType: 976 return getNamedFunction("fieldType", CLS_OBJ_TYPE); 977 case NF_staticFieldType: 978 return getNamedFunction("staticFieldType", CLS_OBJ_TYPE); 979 case NF_nullCheck: 980 return getNamedFunction("nullCheck", OBJ_OBJ_TYPE); 981 case NF_fieldLayout: 982 return getNamedFunction("fieldLayout", INT_OBJ_TYPE); 983 default: 984 throw newInternalError("Unknown function: " + func); 985 } 986 } catch (ReflectiveOperationException ex) { 987 throw newInternalError(ex); 988 } 989 } 990 991 private static NamedFunction getNamedFunction(String name, MethodType type) 992 throws ReflectiveOperationException 993 { 994 MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic); 995 return new NamedFunction( 996 MemberName.getFactory().resolveOrFail(REF_invokeStatic, member, 997 DirectMethodHandle.class, LM_TRUSTED, 998 NoSuchMethodException.class)); 999 } 1000 1001 static { 1002 // The Holder class will contain pre-generated DirectMethodHandles resolved 1003 // speculatively using MemberName.getFactory().resolveOrNull. However, that 1004 // doesn't initialize the class, which subtly breaks inlining etc. By forcing 1005 // initialization of the Holder class we avoid these issues. 1006 UNSAFE.ensureClassInitialized(Holder.class); 1007 } 1008 1009 /* Placeholder class for DirectMethodHandles generated ahead of time */ 1010 final class Holder {} 1011 }