1 /* 2 * Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.misc.Unsafe; 29 import jdk.internal.vm.annotation.ForceInline; 30 import jdk.internal.vm.annotation.Stable; 31 import sun.invoke.util.ValueConversions; 32 import sun.invoke.util.VerifyAccess; 33 import sun.invoke.util.Wrapper; 34 35 import java.util.Arrays; 36 import java.util.Objects; 37 import java.util.function.Function; 38 39 import static java.lang.invoke.LambdaForm.*; 40 import static java.lang.invoke.LambdaForm.Kind.*; 41 import static java.lang.invoke.MethodHandleNatives.Constants.*; 42 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 43 import static java.lang.invoke.MethodHandleStatics.newInternalError; 44 import static java.lang.invoke.MethodTypeForm.*; 45 46 /** 47 * The flavor of method handle which implements a constant reference 48 * to a class member. 49 * @author jrose 50 */ 51 sealed class DirectMethodHandle extends MethodHandle { 52 final MemberName member; 53 final boolean crackable; 54 55 // Constructors and factory methods in this class *must* be package scoped or private. 56 private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member, boolean crackable) { 57 super(mtype, form); 58 if (!member.isResolved()) throw new InternalError(); 59 60 if (member.getDeclaringClass().isInterface() && 61 member.getReferenceKind() == REF_invokeInterface && 62 member.isMethod() && !member.isAbstract()) { 63 // Check for corner case: invokeinterface of Object method 64 MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind()); 65 m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null, LM_TRUSTED); 66 if (m != null && m.isPublic()) { 67 assert(member.getReferenceKind() == m.getReferenceKind()); // else this.form is wrong 68 member = m; 69 } 70 } 71 72 this.member = member; 73 this.crackable = crackable; 74 } 75 76 // Factory methods: 77 static DirectMethodHandle make(byte refKind, Class<?> refc, MemberName member, Class<?> callerClass) { 78 MethodType mtype = member.getMethodOrFieldType(); 79 if (!member.isStatic()) { 80 if (!member.getDeclaringClass().isAssignableFrom(refc) || member.isConstructor()) 81 throw new InternalError(member.toString()); 82 mtype = mtype.insertParameterTypes(0, refc); 83 } 84 if (!member.isField()) { 85 // refKind reflects the original type of lookup via findSpecial or 86 // findVirtual etc. 87 return switch (refKind) { 88 case REF_invokeSpecial -> { 89 member = member.asSpecial(); 90 // if caller is an interface we need to adapt to get the 91 // receiver check inserted 92 if (callerClass == null) { 93 throw new InternalError("callerClass must not be null for REF_invokeSpecial"); 94 } 95 LambdaForm lform = preparedLambdaForm(member, callerClass.isInterface()); 96 yield new Special(mtype, lform, member, true, callerClass); 97 } 98 case REF_invokeInterface -> { 99 // for interfaces we always need the receiver typecheck, 100 // so we always pass 'true' to ensure we adapt if needed 101 // to include the REF_invokeSpecial case 102 LambdaForm lform = preparedLambdaForm(member, true); 103 yield new Interface(mtype, lform, member, true, refc); 104 } 105 default -> { 106 LambdaForm lform = preparedLambdaForm(member); 107 yield new DirectMethodHandle(mtype, lform, member, true); 108 } 109 }; 110 } else { 111 LambdaForm lform = preparedFieldLambdaForm(member); 112 if (member.isStatic()) { 113 long offset = MethodHandleNatives.staticFieldOffset(member); 114 Object base = MethodHandleNatives.staticFieldBase(member); 115 return new StaticAccessor(mtype, lform, member, true, base, offset); 116 } else { 117 long offset = MethodHandleNatives.objectFieldOffset(member); 118 assert(offset == (int)offset); 119 return new Accessor(mtype, lform, member, true, (int)offset); 120 } 121 } 122 } 123 static DirectMethodHandle make(Class<?> refc, MemberName member) { 124 byte refKind = member.getReferenceKind(); 125 if (refKind == REF_invokeSpecial) 126 refKind = REF_invokeVirtual; 127 return make(refKind, refc, member, null /* no callerClass context */); 128 } 129 static DirectMethodHandle make(MemberName member) { 130 if (member.isConstructor()) 131 return makeAllocator(member.getDeclaringClass(), member); 132 return make(member.getDeclaringClass(), member); 133 } 134 static DirectMethodHandle makeAllocator(Class<?> instanceClass, MemberName ctor) { 135 assert(ctor.isConstructor()) : ctor; 136 ctor = ctor.asConstructor(); 137 assert(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 final int layout; 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 this.layout = member.getLayout(); 520 } 521 522 @Override Object checkCast(Object obj) { 523 return fieldType.cast(obj); 524 } 525 @Override 526 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 527 return new Accessor(mt, lf, member, crackable, fieldOffset); 528 } 529 @Override 530 MethodHandle viewAsType(MethodType newType, boolean strict) { 531 assert(viewAsTypeChecks(newType, strict)); 532 return new Accessor(newType, form, member, false, fieldOffset); 533 } 534 } 535 536 @ForceInline 537 /*non-public*/ 538 static long fieldOffset(Object accessorObj) { 539 // Note: We return a long because that is what Unsafe.getObject likes. 540 // We store a plain int because it is more compact. 541 return ((Accessor)accessorObj).fieldOffset; 542 } 543 544 @ForceInline 545 /*non-public*/ 546 static Object checkBase(Object obj) { 547 // Note that the object's class has already been verified, 548 // since the parameter type of the Accessor method handle 549 // is either member.getDeclaringClass or a subclass. 550 // This was verified in DirectMethodHandle.make. 551 // Therefore, the only remaining check is for null. 552 // Since this check is *not* guaranteed by Unsafe.getInt 553 // and its siblings, we need to make an explicit one here. 554 return Objects.requireNonNull(obj); 555 } 556 557 /** This subclass handles static field references. */ 558 static final class StaticAccessor extends DirectMethodHandle { 559 private final Class<?> fieldType; 560 private final Object staticBase; 561 private final long staticOffset; 562 563 private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member, 564 boolean crackable, Object staticBase, long staticOffset) { 565 super(mtype, form, member, crackable); 566 this.fieldType = member.getFieldType(); 567 this.staticBase = staticBase; 568 this.staticOffset = staticOffset; 569 } 570 571 @Override Object checkCast(Object obj) { 572 return fieldType.cast(obj); 573 } 574 @Override 575 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 576 return new StaticAccessor(mt, lf, member, crackable, staticBase, staticOffset); 577 } 578 @Override 579 MethodHandle viewAsType(MethodType newType, boolean strict) { 580 assert(viewAsTypeChecks(newType, strict)); 581 return new StaticAccessor(newType, form, member, false, staticBase, staticOffset); 582 } 583 } 584 585 @ForceInline 586 /*non-public*/ 587 static Object nullCheck(Object obj) { 588 return Objects.requireNonNull(obj); 589 } 590 591 @ForceInline 592 /*non-public*/ 593 static Object staticBase(Object accessorObj) { 594 return ((StaticAccessor)accessorObj).staticBase; 595 } 596 597 @ForceInline 598 /*non-public*/ 599 static long staticOffset(Object accessorObj) { 600 return ((StaticAccessor)accessorObj).staticOffset; 601 } 602 603 @ForceInline 604 /*non-public*/ 605 static Object checkCast(Object mh, Object obj) { 606 return ((DirectMethodHandle) mh).checkCast(obj); 607 } 608 609 @ForceInline 610 /*non-public*/ static Class<?> fieldType(Object accessorObj) { 611 return ((Accessor) accessorObj).fieldType; 612 } 613 614 @ForceInline 615 static int fieldLayout(Object accessorObj) { 616 return ((Accessor) accessorObj).layout; 617 } 618 619 @ForceInline 620 /*non-public*/ static Class<?> staticFieldType(Object accessorObj) { 621 return ((StaticAccessor) accessorObj).fieldType; 622 } 623 624 @ForceInline 625 /*non-public*/ static Object zeroInstanceIfNull(Class<?> fieldType, Object obj) { 626 return obj != null ? obj : UNSAFE.uninitializedDefaultValue(fieldType); 627 } 628 629 Object checkCast(Object obj) { 630 return member.getMethodType().returnType().cast(obj); 631 } 632 633 // Caching machinery for field accessors: 634 static final byte 635 AF_GETFIELD = 0, 636 AF_PUTFIELD = 1, 637 AF_GETSTATIC = 2, 638 AF_PUTSTATIC = 3, 639 AF_GETSTATIC_INIT = 4, 640 AF_PUTSTATIC_INIT = 5, 641 AF_LIMIT = 6; 642 // Enumerate the different field kinds using Wrapper, 643 // with an extra case added for checked references and value field access 644 static final int 645 FT_LAST_WRAPPER = Wrapper.COUNT-1, 646 FT_UNCHECKED_REF = Wrapper.OBJECT.ordinal(), 647 FT_CHECKED_REF = FT_LAST_WRAPPER+1, 648 FT_CHECKED_VALUE = FT_LAST_WRAPPER+2, // flat vs non-flat x null value vs null-restricted value 649 FT_LIMIT = FT_LAST_WRAPPER+6; 650 private static int afIndex(byte formOp, boolean isVolatile, boolean isFlat, boolean isNullRestricted, int ftypeKind) { 651 return ((formOp * FT_LIMIT * 2) 652 + (isVolatile ? FT_LIMIT : 0) 653 + (isFlat ? 1 : 0) 654 + (isNullRestricted ? 1 : 0) 655 + ftypeKind); 656 } 657 @Stable 658 private static final LambdaForm[] ACCESSOR_FORMS 659 = new LambdaForm[afIndex(AF_LIMIT, false, false, false, 0)]; 660 static int ftypeKind(Class<?> ftype) { 661 if (ftype.isPrimitive()) { 662 return Wrapper.forPrimitiveType(ftype).ordinal(); 663 } else if (ftype.isInterface() || ftype.isAssignableFrom(Object.class)) { 664 // retyping can be done without a cast 665 return FT_UNCHECKED_REF; 666 } else { 667 return ftype.isValue() ? FT_CHECKED_VALUE : FT_CHECKED_REF; 668 } 669 } 670 671 /** 672 * Create a LF which can access the given field. 673 * Cache and share this structure among all fields with 674 * the same basicType and refKind. 675 */ 676 private static LambdaForm preparedFieldLambdaForm(MemberName m) { 677 Class<?> ftype = m.getFieldType(); 678 byte formOp = switch (m.getReferenceKind()) { 679 case REF_getField -> AF_GETFIELD; 680 case REF_putField -> AF_PUTFIELD; 681 case REF_getStatic -> AF_GETSTATIC; 682 case REF_putStatic -> AF_PUTSTATIC; 683 default -> throw new InternalError(m.toString()); 684 }; 685 if (shouldBeInitialized(m)) { 686 // precompute the barrier-free version: 687 preparedFieldLambdaForm(formOp, m.isVolatile(), m.isFlat(), m.isNullRestricted(), ftype); 688 assert((AF_GETSTATIC_INIT - AF_GETSTATIC) == 689 (AF_PUTSTATIC_INIT - AF_PUTSTATIC)); 690 formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC); 691 } 692 LambdaForm lform = preparedFieldLambdaForm(formOp, m.isVolatile(), m.isFlat(), m.isNullRestricted(), ftype); 693 maybeCompile(lform, m); 694 assert(lform.methodType().dropParameterTypes(0, 1) 695 .equals(m.getInvocationType().basicType())) 696 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 697 return lform; 698 } 699 700 private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, 701 boolean isFlat, boolean isNullRestricted, Class<?> ftype) { 702 int ftypeKind = ftypeKind(ftype); 703 int afIndex = afIndex(formOp, isVolatile, isFlat, isNullRestricted, ftypeKind); 704 LambdaForm lform = ACCESSOR_FORMS[afIndex]; 705 if (lform != null) return lform; 706 lform = makePreparedFieldLambdaForm(formOp, isVolatile,isFlat, isNullRestricted, ftypeKind); 707 ACCESSOR_FORMS[afIndex] = lform; // don't bother with a CAS 708 return lform; 709 } 710 711 private static final Wrapper[] ALL_WRAPPERS = Wrapper.values(); 712 713 private static Kind getFieldKind(boolean isGetter, boolean isVolatile, boolean isFlat, Wrapper wrapper) { 714 if (isGetter) { 715 if (isVolatile) { 716 switch (wrapper) { 717 case BOOLEAN: return GET_BOOLEAN_VOLATILE; 718 case BYTE: return GET_BYTE_VOLATILE; 719 case SHORT: return GET_SHORT_VOLATILE; 720 case CHAR: return GET_CHAR_VOLATILE; 721 case INT: return GET_INT_VOLATILE; 722 case LONG: return GET_LONG_VOLATILE; 723 case FLOAT: return GET_FLOAT_VOLATILE; 724 case DOUBLE: return GET_DOUBLE_VOLATILE; 725 case OBJECT: return isFlat ? GET_FLAT_VALUE_VOLATILE : GET_REFERENCE_VOLATILE; 726 } 727 } else { 728 switch (wrapper) { 729 case BOOLEAN: return GET_BOOLEAN; 730 case BYTE: return GET_BYTE; 731 case SHORT: return GET_SHORT; 732 case CHAR: return GET_CHAR; 733 case INT: return GET_INT; 734 case LONG: return GET_LONG; 735 case FLOAT: return GET_FLOAT; 736 case DOUBLE: return GET_DOUBLE; 737 case OBJECT: return isFlat ? GET_FLAT_VALUE : GET_REFERENCE; 738 } 739 } 740 } else { 741 if (isVolatile) { 742 switch (wrapper) { 743 case BOOLEAN: return PUT_BOOLEAN_VOLATILE; 744 case BYTE: return PUT_BYTE_VOLATILE; 745 case SHORT: return PUT_SHORT_VOLATILE; 746 case CHAR: return PUT_CHAR_VOLATILE; 747 case INT: return PUT_INT_VOLATILE; 748 case LONG: return PUT_LONG_VOLATILE; 749 case FLOAT: return PUT_FLOAT_VOLATILE; 750 case DOUBLE: return PUT_DOUBLE_VOLATILE; 751 case OBJECT: return isFlat ? PUT_FLAT_VALUE_VOLATILE : PUT_REFERENCE_VOLATILE; 752 } 753 } else { 754 switch (wrapper) { 755 case BOOLEAN: return PUT_BOOLEAN; 756 case BYTE: return PUT_BYTE; 757 case SHORT: return PUT_SHORT; 758 case CHAR: return PUT_CHAR; 759 case INT: return PUT_INT; 760 case LONG: return PUT_LONG; 761 case FLOAT: return PUT_FLOAT; 762 case DOUBLE: return PUT_DOUBLE; 763 case OBJECT: return isFlat ? PUT_FLAT_VALUE : PUT_REFERENCE; 764 } 765 } 766 } 767 throw new AssertionError("Invalid arguments"); 768 } 769 770 /** invoked by GenerateJLIClassesHelper */ 771 static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftype) { 772 return makePreparedFieldLambdaForm(formOp, isVolatile, false, false, ftype); 773 } 774 775 private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, 776 boolean isFlat, boolean isNullRestricted, int ftypeKind) { 777 boolean isGetter = (formOp & 1) == (AF_GETFIELD & 1); 778 boolean isStatic = (formOp >= AF_GETSTATIC); 779 boolean needsInit = (formOp >= AF_GETSTATIC_INIT); 780 boolean needsCast = (ftypeKind == FT_CHECKED_REF || ftypeKind == FT_CHECKED_VALUE); 781 Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]); 782 Class<?> ft = fw.primitiveType(); 783 assert(needsCast ? true : ftypeKind(ft) == ftypeKind); 784 785 // getObject, putIntVolatile, etc. 786 Kind kind = getFieldKind(isGetter, isVolatile, isFlat, fw); 787 788 MethodType linkerType; 789 if (isGetter) { 790 linkerType = isFlat 791 ? MethodType.methodType(ft, Object.class, long.class, int.class, Class.class) 792 : MethodType.methodType(ft, Object.class, long.class); 793 } else { 794 linkerType = isFlat 795 ? MethodType.methodType(void.class, Object.class, long.class, int.class, Class.class, ft) 796 : MethodType.methodType(void.class, Object.class, long.class, ft); 797 } 798 MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual); 799 try { 800 linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, LM_TRUSTED, 801 NoSuchMethodException.class); 802 } catch (ReflectiveOperationException ex) { 803 throw newInternalError(ex); 804 } 805 806 // What is the external type of the lambda form? 807 MethodType mtype; 808 if (isGetter) 809 mtype = MethodType.methodType(ft); 810 else 811 mtype = MethodType.methodType(void.class, ft); 812 mtype = mtype.basicType(); // erase short to int, etc. 813 if (!isStatic) 814 mtype = mtype.insertParameterTypes(0, Object.class); 815 final int DMH_THIS = 0; 816 final int ARG_BASE = 1; 817 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 818 // if this is for non-static access, the base pointer is stored at this index: 819 final int OBJ_BASE = isStatic ? -1 : ARG_BASE; 820 // if this is for write access, the value to be written is stored at this index: 821 final int SET_VALUE = isGetter ? -1 : ARG_LIMIT - 1; 822 int nameCursor = ARG_LIMIT; 823 final int F_HOLDER = (isStatic ? nameCursor++ : -1); // static base if any 824 final int F_OFFSET = nameCursor++; // Either static offset or field offset. 825 final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1); 826 final int U_HOLDER = nameCursor++; // UNSAFE holder 827 final int INIT_BAR = (needsInit ? nameCursor++ : -1); 828 final int LAYOUT = (isFlat ? nameCursor++ : -1); // field must be instance 829 final int VALUE_TYPE = (isFlat ? nameCursor++ : -1); 830 final int NULL_CHECK = (isNullRestricted && !isGetter ? nameCursor++ : -1); 831 final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1); 832 final int LINKER_CALL = nameCursor++; 833 final int FIELD_TYPE = (isNullRestricted && isGetter ? nameCursor++ : -1); 834 final int ZERO_INSTANCE = (isNullRestricted && isGetter ? nameCursor++ : -1); 835 final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1); 836 final int RESULT = nameCursor-1; // either the call, zero instance, or the cast 837 Name[] names = invokeArguments(nameCursor - ARG_LIMIT, mtype); 838 if (needsInit) 839 names[INIT_BAR] = new Name(getFunction(NF_ensureInitialized), names[DMH_THIS]); 840 if (!isGetter) { 841 if (isNullRestricted) 842 names[NULL_CHECK] = new Name(getFunction(NF_nullCheck), names[SET_VALUE]); 843 if (needsCast) 844 names[PRE_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[SET_VALUE]); 845 } 846 Object[] outArgs = new Object[1 + linkerType.parameterCount()]; 847 assert (outArgs.length == (isGetter ? 3 : 4) + (isFlat ? 2 : 0)); 848 outArgs[0] = names[U_HOLDER] = new Name(getFunction(NF_UNSAFE)); 849 if (isStatic) { 850 outArgs[1] = names[F_HOLDER] = new Name(getFunction(NF_staticBase), names[DMH_THIS]); 851 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_staticOffset), names[DMH_THIS]); 852 } else { 853 outArgs[1] = names[OBJ_CHECK] = new Name(getFunction(NF_checkBase), names[OBJ_BASE]); 854 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_fieldOffset), names[DMH_THIS]); 855 } 856 int x = 3; 857 if (isFlat) { 858 assert !isStatic : "static field is flat form requested"; 859 outArgs[x++] = names[LAYOUT] = new Name(getFunction(NF_fieldLayout), names[DMH_THIS]); 860 outArgs[x++] = names[VALUE_TYPE] = isStatic ? new Name(getFunction(NF_staticFieldType), names[DMH_THIS]) 861 : new Name(getFunction(NF_fieldType), names[DMH_THIS]); 862 } 863 if (!isGetter) { 864 outArgs[x] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]); 865 } 866 for (Object a : outArgs) assert(a != null); 867 names[LINKER_CALL] = new Name(linker, outArgs); 868 if (isGetter) { 869 int argIndex = LINKER_CALL; 870 if (isNullRestricted) { 871 names[FIELD_TYPE] = isStatic ? new Name(getFunction(NF_staticFieldType), names[DMH_THIS]) 872 : new Name(getFunction(NF_fieldType), names[DMH_THIS]); 873 names[ZERO_INSTANCE] = new Name(getFunction(NF_zeroInstance), names[FIELD_TYPE], names[LINKER_CALL]); 874 argIndex = ZERO_INSTANCE; 875 } 876 if (needsCast) 877 names[POST_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[argIndex]); 878 } 879 for (Name n : names) assert(n != null); 880 881 LambdaForm form; 882 if (needsCast || needsInit) { 883 // can't use the pre-generated form when casting and/or initializing 884 form = LambdaForm.create(ARG_LIMIT, names, RESULT); 885 } else { 886 form = LambdaForm.create(ARG_LIMIT, names, RESULT, kind); 887 } 888 889 if (LambdaForm.debugNames()) { 890 // add some detail to the lambdaForm debugname, 891 // significant only for debugging 892 StringBuilder nameBuilder = new StringBuilder(kind.methodName); 893 if (isStatic) { 894 nameBuilder.append("Static"); 895 } else { 896 nameBuilder.append("Field"); 897 } 898 if (needsCast) { 899 nameBuilder.append("Cast"); 900 } 901 if (needsInit) { 902 nameBuilder.append("Init"); 903 } 904 LambdaForm.associateWithDebugName(form, nameBuilder.toString()); 905 } 906 return form; 907 } 908 909 /** 910 * Pre-initialized NamedFunctions for bootstrapping purposes. 911 */ 912 static final byte NF_internalMemberName = 0, 913 NF_internalMemberNameEnsureInit = 1, 914 NF_ensureInitialized = 2, 915 NF_fieldOffset = 3, 916 NF_checkBase = 4, 917 NF_staticBase = 5, 918 NF_staticOffset = 6, 919 NF_checkCast = 7, 920 NF_allocateInstance = 8, 921 NF_constructorMethod = 9, 922 NF_UNSAFE = 10, 923 NF_checkReceiver = 11, 924 NF_fieldType = 12, 925 NF_staticFieldType = 13, 926 NF_zeroInstance = 14, 927 NF_nullCheck = 15, 928 NF_fieldLayout = 16, 929 NF_LIMIT = 17; 930 931 private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT]; 932 933 private static NamedFunction getFunction(byte func) { 934 NamedFunction nf = NFS[func]; 935 if (nf != null) { 936 return nf; 937 } 938 // Each nf must be statically invocable or we get tied up in our bootstraps. 939 nf = NFS[func] = createFunction(func); 940 assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf)); 941 return nf; 942 } 943 944 private static final MethodType CLS_OBJ_TYPE = MethodType.methodType(Class.class, Object.class); 945 private static final MethodType INT_OBJ_TYPE = MethodType.methodType(int.class, Object.class); 946 947 private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class); 948 949 private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class); 950 951 private static NamedFunction createFunction(byte func) { 952 try { 953 switch (func) { 954 case NF_internalMemberName: 955 return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE); 956 case NF_internalMemberNameEnsureInit: 957 return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE); 958 case NF_ensureInitialized: 959 return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class)); 960 case NF_fieldOffset: 961 return getNamedFunction("fieldOffset", LONG_OBJ_TYPE); 962 case NF_checkBase: 963 return getNamedFunction("checkBase", OBJ_OBJ_TYPE); 964 case NF_staticBase: 965 return getNamedFunction("staticBase", OBJ_OBJ_TYPE); 966 case NF_staticOffset: 967 return getNamedFunction("staticOffset", LONG_OBJ_TYPE); 968 case NF_checkCast: 969 return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class)); 970 case NF_allocateInstance: 971 return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE); 972 case NF_constructorMethod: 973 return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE); 974 case NF_UNSAFE: 975 MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getStatic); 976 return new NamedFunction( 977 MemberName.getFactory().resolveOrFail(REF_getStatic, member, 978 DirectMethodHandle.class, LM_TRUSTED, 979 NoSuchFieldException.class)); 980 case NF_checkReceiver: 981 member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual); 982 return new NamedFunction( 983 MemberName.getFactory().resolveOrFail(REF_invokeVirtual, member, 984 DirectMethodHandle.class, LM_TRUSTED, 985 NoSuchMethodException.class)); 986 case NF_fieldType: 987 return getNamedFunction("fieldType", CLS_OBJ_TYPE); 988 case NF_staticFieldType: 989 return getNamedFunction("staticFieldType", CLS_OBJ_TYPE); 990 case NF_zeroInstance: 991 return getNamedFunction("zeroInstanceIfNull", MethodType.methodType(Object.class, Class.class, Object.class)); 992 case NF_nullCheck: 993 return getNamedFunction("nullCheck", OBJ_OBJ_TYPE); 994 case NF_fieldLayout: 995 return getNamedFunction("fieldLayout", INT_OBJ_TYPE); 996 default: 997 throw newInternalError("Unknown function: " + func); 998 } 999 } catch (ReflectiveOperationException ex) { 1000 throw newInternalError(ex); 1001 } 1002 } 1003 1004 private static NamedFunction getNamedFunction(String name, MethodType type) 1005 throws ReflectiveOperationException 1006 { 1007 MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic); 1008 return new NamedFunction( 1009 MemberName.getFactory().resolveOrFail(REF_invokeStatic, member, 1010 DirectMethodHandle.class, LM_TRUSTED, 1011 NoSuchMethodException.class)); 1012 } 1013 1014 static { 1015 // The Holder class will contain pre-generated DirectMethodHandles resolved 1016 // speculatively using MemberName.getFactory().resolveOrNull. However, that 1017 // doesn't initialize the class, which subtly breaks inlining etc. By forcing 1018 // initialization of the Holder class we avoid these issues. 1019 UNSAFE.ensureClassInitialized(Holder.class); 1020 } 1021 1022 /* Placeholder class for DirectMethodHandles generated ahead of time */ 1023 final class Holder {} 1024 }