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.getName().equals("<init>")); 137 ctor = ctor.asConstructor(); 138 assert(ctor.isConstructor() && 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 private Accessor(MethodType mtype, LambdaForm form, MemberName member, 515 boolean crackable, int fieldOffset) { 516 super(mtype, form, member, crackable); 517 this.fieldType = member.getFieldType(); 518 this.fieldOffset = fieldOffset; 519 } 520 521 @Override Object checkCast(Object obj) { 522 return fieldType.cast(obj); 523 } 524 @Override 525 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 526 return new Accessor(mt, lf, member, crackable, fieldOffset); 527 } 528 @Override 529 MethodHandle viewAsType(MethodType newType, boolean strict) { 530 assert(viewAsTypeChecks(newType, strict)); 531 return new Accessor(newType, form, member, false, fieldOffset); 532 } 533 } 534 535 @ForceInline 536 /*non-public*/ 537 static long fieldOffset(Object accessorObj) { 538 // Note: We return a long because that is what Unsafe.getObject likes. 539 // We store a plain int because it is more compact. 540 return ((Accessor)accessorObj).fieldOffset; 541 } 542 543 @ForceInline 544 /*non-public*/ 545 static Object checkBase(Object obj) { 546 // Note that the object's class has already been verified, 547 // since the parameter type of the Accessor method handle 548 // is either member.getDeclaringClass or a subclass. 549 // This was verified in DirectMethodHandle.make. 550 // Therefore, the only remaining check is for null. 551 // Since this check is *not* guaranteed by Unsafe.getInt 552 // and its siblings, we need to make an explicit one here. 553 return Objects.requireNonNull(obj); 554 } 555 556 /** This subclass handles static field references. */ 557 static final class StaticAccessor extends DirectMethodHandle { 558 private final Class<?> fieldType; 559 private final Object staticBase; 560 private final long staticOffset; 561 562 private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member, 563 boolean crackable, Object staticBase, long staticOffset) { 564 super(mtype, form, member, crackable); 565 this.fieldType = member.getFieldType(); 566 this.staticBase = staticBase; 567 this.staticOffset = staticOffset; 568 } 569 570 @Override Object checkCast(Object obj) { 571 return fieldType.cast(obj); 572 } 573 @Override 574 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 575 return new StaticAccessor(mt, lf, member, crackable, staticBase, staticOffset); 576 } 577 @Override 578 MethodHandle viewAsType(MethodType newType, boolean strict) { 579 assert(viewAsTypeChecks(newType, strict)); 580 return new StaticAccessor(newType, form, member, false, staticBase, staticOffset); 581 } 582 } 583 584 @ForceInline 585 /*non-public*/ 586 static Object nullCheck(Object obj) { 587 return Objects.requireNonNull(obj); 588 } 589 590 @ForceInline 591 /*non-public*/ 592 static Object staticBase(Object accessorObj) { 593 return ((StaticAccessor)accessorObj).staticBase; 594 } 595 596 @ForceInline 597 /*non-public*/ 598 static long staticOffset(Object accessorObj) { 599 return ((StaticAccessor)accessorObj).staticOffset; 600 } 601 602 @ForceInline 603 /*non-public*/ 604 static Object checkCast(Object mh, Object obj) { 605 return ((DirectMethodHandle) mh).checkCast(obj); 606 } 607 608 Object checkCast(Object obj) { 609 return member.getMethodType().returnType().cast(obj); 610 } 611 612 // Caching machinery for field accessors: 613 static final byte 614 AF_GETFIELD = 0, 615 AF_PUTFIELD = 1, 616 AF_GETSTATIC = 2, 617 AF_PUTSTATIC = 3, 618 AF_GETSTATIC_INIT = 4, 619 AF_PUTSTATIC_INIT = 5, 620 AF_LIMIT = 6; 621 // Enumerate the different field kinds using Wrapper, 622 // with an extra case added for checked references. 623 static final int 624 FT_LAST_WRAPPER = Wrapper.COUNT-1, 625 FT_UNCHECKED_REF = Wrapper.OBJECT.ordinal(), 626 FT_CHECKED_REF = FT_LAST_WRAPPER+1, 627 FT_LIMIT = FT_LAST_WRAPPER+2; 628 private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) { 629 return ((formOp * FT_LIMIT * 2) 630 + (isVolatile ? FT_LIMIT : 0) 631 + ftypeKind); 632 } 633 @Stable 634 private static final LambdaForm[] ACCESSOR_FORMS 635 = new LambdaForm[afIndex(AF_LIMIT, false, 0)]; 636 static int ftypeKind(Class<?> ftype) { 637 if (ftype.isPrimitive()) { 638 return Wrapper.forPrimitiveType(ftype).ordinal(); 639 } else if (ftype.isInterface() || ftype.isAssignableFrom(Object.class)) { 640 // retyping can be done without a cast 641 return FT_UNCHECKED_REF; 642 } else { 643 return FT_CHECKED_REF; 644 } 645 } 646 647 /** 648 * Create a LF which can access the given field. 649 * Cache and share this structure among all fields with 650 * the same basicType and refKind. 651 */ 652 private static LambdaForm preparedFieldLambdaForm(MemberName m) { 653 Class<?> ftype = m.getFieldType(); 654 boolean isVolatile = m.isVolatile(); 655 byte formOp = switch (m.getReferenceKind()) { 656 case REF_getField -> AF_GETFIELD; 657 case REF_putField -> AF_PUTFIELD; 658 case REF_getStatic -> AF_GETSTATIC; 659 case REF_putStatic -> AF_PUTSTATIC; 660 default -> throw new InternalError(m.toString()); 661 }; 662 if (shouldBeInitialized(m)) { 663 // precompute the barrier-free version: 664 preparedFieldLambdaForm(formOp, isVolatile, ftype); 665 assert((AF_GETSTATIC_INIT - AF_GETSTATIC) == 666 (AF_PUTSTATIC_INIT - AF_PUTSTATIC)); 667 formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC); 668 } 669 LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype); 670 maybeCompile(lform, m); 671 assert(lform.methodType().dropParameterTypes(0, 1) 672 .equals(m.getInvocationType().basicType())) 673 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 674 return lform; 675 } 676 private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) { 677 int ftypeKind = ftypeKind(ftype); 678 int afIndex = afIndex(formOp, isVolatile, ftypeKind); 679 LambdaForm lform = ACCESSOR_FORMS[afIndex]; 680 if (lform != null) return lform; 681 lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind); 682 ACCESSOR_FORMS[afIndex] = lform; // don't bother with a CAS 683 return lform; 684 } 685 686 private static final Wrapper[] ALL_WRAPPERS = Wrapper.values(); 687 688 private static Kind getFieldKind(boolean isGetter, boolean isVolatile, Wrapper wrapper) { 689 if (isGetter) { 690 if (isVolatile) { 691 switch (wrapper) { 692 case BOOLEAN: return GET_BOOLEAN_VOLATILE; 693 case BYTE: return GET_BYTE_VOLATILE; 694 case SHORT: return GET_SHORT_VOLATILE; 695 case CHAR: return GET_CHAR_VOLATILE; 696 case INT: return GET_INT_VOLATILE; 697 case LONG: return GET_LONG_VOLATILE; 698 case FLOAT: return GET_FLOAT_VOLATILE; 699 case DOUBLE: return GET_DOUBLE_VOLATILE; 700 case OBJECT: return GET_REFERENCE_VOLATILE; 701 } 702 } else { 703 switch (wrapper) { 704 case BOOLEAN: return GET_BOOLEAN; 705 case BYTE: return GET_BYTE; 706 case SHORT: return GET_SHORT; 707 case CHAR: return GET_CHAR; 708 case INT: return GET_INT; 709 case LONG: return GET_LONG; 710 case FLOAT: return GET_FLOAT; 711 case DOUBLE: return GET_DOUBLE; 712 case OBJECT: return GET_REFERENCE; 713 } 714 } 715 } else { 716 if (isVolatile) { 717 switch (wrapper) { 718 case BOOLEAN: return PUT_BOOLEAN_VOLATILE; 719 case BYTE: return PUT_BYTE_VOLATILE; 720 case SHORT: return PUT_SHORT_VOLATILE; 721 case CHAR: return PUT_CHAR_VOLATILE; 722 case INT: return PUT_INT_VOLATILE; 723 case LONG: return PUT_LONG_VOLATILE; 724 case FLOAT: return PUT_FLOAT_VOLATILE; 725 case DOUBLE: return PUT_DOUBLE_VOLATILE; 726 case OBJECT: return PUT_REFERENCE_VOLATILE; 727 } 728 } else { 729 switch (wrapper) { 730 case BOOLEAN: return PUT_BOOLEAN; 731 case BYTE: return PUT_BYTE; 732 case SHORT: return PUT_SHORT; 733 case CHAR: return PUT_CHAR; 734 case INT: return PUT_INT; 735 case LONG: return PUT_LONG; 736 case FLOAT: return PUT_FLOAT; 737 case DOUBLE: return PUT_DOUBLE; 738 case OBJECT: return PUT_REFERENCE; 739 } 740 } 741 } 742 throw new AssertionError("Invalid arguments"); 743 } 744 745 static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) { 746 boolean isGetter = (formOp & 1) == (AF_GETFIELD & 1); 747 boolean isStatic = (formOp >= AF_GETSTATIC); 748 boolean needsInit = (formOp >= AF_GETSTATIC_INIT); 749 boolean needsCast = (ftypeKind == FT_CHECKED_REF); 750 Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]); 751 Class<?> ft = fw.primitiveType(); 752 assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind); 753 754 // getObject, putIntVolatile, etc. 755 Kind kind = getFieldKind(isGetter, isVolatile, fw); 756 757 MethodType linkerType; 758 if (isGetter) 759 linkerType = MethodType.methodType(ft, Object.class, long.class); 760 else 761 linkerType = MethodType.methodType(void.class, Object.class, long.class, ft); 762 MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual); 763 try { 764 linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, LM_TRUSTED, 765 NoSuchMethodException.class); 766 } catch (ReflectiveOperationException ex) { 767 throw newInternalError(ex); 768 } 769 770 // What is the external type of the lambda form? 771 MethodType mtype; 772 if (isGetter) 773 mtype = MethodType.methodType(ft); 774 else 775 mtype = MethodType.methodType(void.class, ft); 776 mtype = mtype.basicType(); // erase short to int, etc. 777 if (!isStatic) 778 mtype = mtype.insertParameterTypes(0, Object.class); 779 final int DMH_THIS = 0; 780 final int ARG_BASE = 1; 781 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 782 // if this is for non-static access, the base pointer is stored at this index: 783 final int OBJ_BASE = isStatic ? -1 : ARG_BASE; 784 // if this is for write access, the value to be written is stored at this index: 785 final int SET_VALUE = isGetter ? -1 : ARG_LIMIT - 1; 786 int nameCursor = ARG_LIMIT; 787 final int F_HOLDER = (isStatic ? nameCursor++ : -1); // static base if any 788 final int F_OFFSET = nameCursor++; // Either static offset or field offset. 789 final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1); 790 final int U_HOLDER = nameCursor++; // UNSAFE holder 791 final int INIT_BAR = (needsInit ? nameCursor++ : -1); 792 final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1); 793 final int LINKER_CALL = nameCursor++; 794 final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1); 795 final int RESULT = nameCursor-1; // either the call or the cast 796 Name[] names = invokeArguments(nameCursor - ARG_LIMIT, mtype); 797 if (needsInit) 798 names[INIT_BAR] = new Name(getFunction(NF_ensureInitialized), names[DMH_THIS]); 799 if (needsCast && !isGetter) 800 names[PRE_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[SET_VALUE]); 801 Object[] outArgs = new Object[1 + linkerType.parameterCount()]; 802 assert(outArgs.length == (isGetter ? 3 : 4)); 803 outArgs[0] = names[U_HOLDER] = new Name(getFunction(NF_UNSAFE)); 804 if (isStatic) { 805 outArgs[1] = names[F_HOLDER] = new Name(getFunction(NF_staticBase), names[DMH_THIS]); 806 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_staticOffset), names[DMH_THIS]); 807 } else { 808 outArgs[1] = names[OBJ_CHECK] = new Name(getFunction(NF_checkBase), names[OBJ_BASE]); 809 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_fieldOffset), names[DMH_THIS]); 810 } 811 if (!isGetter) { 812 outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]); 813 } 814 for (Object a : outArgs) assert(a != null); 815 names[LINKER_CALL] = new Name(linker, outArgs); 816 if (needsCast && isGetter) 817 names[POST_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[LINKER_CALL]); 818 for (Name n : names) assert(n != null); 819 820 LambdaForm form; 821 if (needsCast || needsInit) { 822 // can't use the pre-generated form when casting and/or initializing 823 form = LambdaForm.create(ARG_LIMIT, names, RESULT); 824 } else { 825 form = LambdaForm.create(ARG_LIMIT, names, RESULT, kind); 826 } 827 828 if (LambdaForm.debugNames()) { 829 // add some detail to the lambdaForm debugname, 830 // significant only for debugging 831 StringBuilder nameBuilder = new StringBuilder(kind.methodName); 832 if (isStatic) { 833 nameBuilder.append("Static"); 834 } else { 835 nameBuilder.append("Field"); 836 } 837 if (needsCast) { 838 nameBuilder.append("Cast"); 839 } 840 if (needsInit) { 841 nameBuilder.append("Init"); 842 } 843 LambdaForm.associateWithDebugName(form, nameBuilder.toString()); 844 } 845 return form; 846 } 847 848 /** 849 * Pre-initialized NamedFunctions for bootstrapping purposes. 850 */ 851 static final byte NF_internalMemberName = 0, 852 NF_internalMemberNameEnsureInit = 1, 853 NF_ensureInitialized = 2, 854 NF_fieldOffset = 3, 855 NF_checkBase = 4, 856 NF_staticBase = 5, 857 NF_staticOffset = 6, 858 NF_checkCast = 7, 859 NF_allocateInstance = 8, 860 NF_constructorMethod = 9, 861 NF_UNSAFE = 10, 862 NF_checkReceiver = 11, 863 NF_LIMIT = 12; 864 865 private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT]; 866 867 private static NamedFunction getFunction(byte func) { 868 NamedFunction nf = NFS[func]; 869 if (nf != null) { 870 return nf; 871 } 872 // Each nf must be statically invocable or we get tied up in our bootstraps. 873 nf = NFS[func] = createFunction(func); 874 assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf)); 875 return nf; 876 } 877 878 private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class); 879 880 private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class); 881 882 private static NamedFunction createFunction(byte func) { 883 try { 884 switch (func) { 885 case NF_internalMemberName: 886 return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE); 887 case NF_internalMemberNameEnsureInit: 888 return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE); 889 case NF_ensureInitialized: 890 return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class)); 891 case NF_fieldOffset: 892 return getNamedFunction("fieldOffset", LONG_OBJ_TYPE); 893 case NF_checkBase: 894 return getNamedFunction("checkBase", OBJ_OBJ_TYPE); 895 case NF_staticBase: 896 return getNamedFunction("staticBase", OBJ_OBJ_TYPE); 897 case NF_staticOffset: 898 return getNamedFunction("staticOffset", LONG_OBJ_TYPE); 899 case NF_checkCast: 900 return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class)); 901 case NF_allocateInstance: 902 return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE); 903 case NF_constructorMethod: 904 return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE); 905 case NF_UNSAFE: 906 MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getStatic); 907 return new NamedFunction( 908 MemberName.getFactory().resolveOrFail(REF_getStatic, member, 909 DirectMethodHandle.class, LM_TRUSTED, 910 NoSuchFieldException.class)); 911 case NF_checkReceiver: 912 member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual); 913 return new NamedFunction( 914 MemberName.getFactory().resolveOrFail(REF_invokeVirtual, member, 915 DirectMethodHandle.class, LM_TRUSTED, 916 NoSuchMethodException.class)); 917 default: 918 throw newInternalError("Unknown function: " + func); 919 } 920 } catch (ReflectiveOperationException ex) { 921 throw newInternalError(ex); 922 } 923 } 924 925 private static NamedFunction getNamedFunction(String name, MethodType type) 926 throws ReflectiveOperationException 927 { 928 MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic); 929 return new NamedFunction( 930 MemberName.getFactory().resolveOrFail(REF_invokeStatic, member, 931 DirectMethodHandle.class, LM_TRUSTED, 932 NoSuchMethodException.class)); 933 } 934 935 static { 936 // The Holder class will contain pre-generated DirectMethodHandles resolved 937 // speculatively using MemberName.getFactory().resolveOrNull. However, that 938 // doesn't initialize the class, which subtly breaks inlining etc. By forcing 939 // initialization of the Holder class we avoid these issues. 940 UNSAFE.ensureClassInitialized(Holder.class); 941 } 942 943 /* Placeholder class for DirectMethodHandles generated ahead of time */ 944 final class Holder {} 945 }