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