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         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     /** Static wrapper for DirectMethodHandle.internalMemberName. */
323     @ForceInline
324     /*non-public*/
325     static Object internalMemberName(Object mh) {
326         return ((DirectMethodHandle)mh).member;
327     }
328 
329     /** Static wrapper for DirectMethodHandle.internalMemberName.
330      * This one also forces initialization.
331      */
332     /*non-public*/
333     static Object internalMemberNameEnsureInit(Object mh) {
334         DirectMethodHandle dmh = (DirectMethodHandle)mh;
335         dmh.ensureInitialized();
336         return dmh.member;
337     }
338 
339     /*non-public*/
340     static boolean shouldBeInitialized(MemberName member) {
341         switch (member.getReferenceKind()) {
342         case REF_invokeStatic:
343         case REF_getStatic:
344         case REF_putStatic:
345         case REF_newInvokeSpecial:
346             break;
347         default:
348             // No need to initialize the class on this kind of member.
349             return false;
350         }
351         Class<?> cls = member.getDeclaringClass();
352         if (cls == ValueConversions.class ||
353             cls == MethodHandleImpl.class ||
354             cls == Invokers.class) {
355             // These guys have lots of <clinit> DMH creation but we know
356             // the MHs will not be used until the system is booted.
357             return false;
358         }
359         if (VerifyAccess.isSamePackage(MethodHandle.class, cls) ||
360             VerifyAccess.isSamePackage(ValueConversions.class, cls)) {
361             // It is a system class.  It is probably in the process of
362             // being initialized, but we will help it along just to be safe.
363             UNSAFE.ensureClassInitialized(cls);
364             return CDS.needsClassInitBarrier(cls);
365         }
366         return UNSAFE.shouldBeInitialized(cls) || CDS.needsClassInitBarrier(cls);
367     }
368 
369     private void ensureInitialized() {
370         if (checkInitialized(member)) {
371             // The coast is clear.  Delete the <clinit> barrier.
372             updateForm(new Function<>() {
373                 public LambdaForm apply(LambdaForm oldForm) {
374                     return (member.isField() ? preparedFieldLambdaForm(member)
375                                              : preparedLambdaForm(member));
376                 }
377             });
378         }
379     }
380     private static boolean checkInitialized(MemberName member) {
381         Class<?> defc = member.getDeclaringClass();
382         UNSAFE.ensureClassInitialized(defc);
383         // Once we get here either defc was fully initialized by another thread, or
384         // defc was already being initialized by the current thread. In the latter case
385         // the barrier must remain. We can detect this simply by checking if initialization
386         // is still needed.
387         return !UNSAFE.shouldBeInitialized(defc);
388     }
389 
390     /*non-public*/
391     static void ensureInitialized(Object mh) {
392         ((DirectMethodHandle)mh).ensureInitialized();
393     }
394 
395     /** This subclass represents invokespecial instructions. */
396     static final class Special extends DirectMethodHandle {
397         private final Class<?> caller;
398         private Special(MethodType mtype, LambdaForm form, MemberName member, boolean crackable, Class<?> caller) {
399             super(mtype, form, member, crackable);
400             this.caller = caller;
401         }
402         @Override
403         boolean isInvokeSpecial() {
404             return true;
405         }
406         @Override
407         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
408             return new Special(mt, lf, member, crackable, caller);
409         }
410         @Override
411         MethodHandle viewAsType(MethodType newType, boolean strict) {
412             assert(viewAsTypeChecks(newType, strict));
413             return new Special(newType, form, member, false, caller);
414         }
415         Object checkReceiver(Object recv) {
416             if (!caller.isInstance(recv)) {
417                 if (recv != null) {
418                     String msg = String.format("Receiver class %s is not a subclass of caller class %s",
419                                                recv.getClass().getName(), caller.getName());
420                     throw new IncompatibleClassChangeError(msg);
421                 } else {
422                     String msg = String.format("Cannot invoke %s with null receiver", member);
423                     throw new NullPointerException(msg);
424                 }
425             }
426             return recv;
427         }
428     }
429 
430     /** This subclass represents invokeinterface instructions. */
431     static final class Interface extends DirectMethodHandle {
432         private final Class<?> refc;
433         private Interface(MethodType mtype, LambdaForm form, MemberName member, boolean crackable, Class<?> refc) {
434             super(mtype, form, member, crackable);
435             assert(refc.isInterface()) : refc;
436             this.refc = refc;
437         }
438         @Override
439         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
440             return new Interface(mt, lf, member, crackable, refc);
441         }
442         @Override
443         MethodHandle viewAsType(MethodType newType, boolean strict) {
444             assert(viewAsTypeChecks(newType, strict));
445             return new Interface(newType, form, member, false, refc);
446         }
447         @Override
448         Object checkReceiver(Object recv) {
449             if (!refc.isInstance(recv)) {
450                 if (recv != null) {
451                     String msg = String.format("Receiver class %s does not implement the requested interface %s",
452                                                recv.getClass().getName(), refc.getName());
453                     throw new IncompatibleClassChangeError(msg);
454                 } else {
455                     String msg = String.format("Cannot invoke %s with null receiver", member);
456                     throw new NullPointerException(msg);
457                 }
458             }
459             return recv;
460         }
461     }
462 
463     /** Used for interface receiver type checks, by Interface and Special modes. */
464     Object checkReceiver(Object recv) {
465         throw new InternalError("Should only be invoked on a subclass");
466     }
467 
468     /** This subclass handles constructor references. */
469     static final class Constructor extends DirectMethodHandle {
470         final MemberName initMethod;
471         final Class<?>   instanceClass;
472 
473         private Constructor(MethodType mtype, LambdaForm form, MemberName constructor,
474                             boolean crackable, MemberName initMethod, Class<?> instanceClass) {
475             super(mtype, form, constructor, crackable);
476             this.initMethod = initMethod;
477             this.instanceClass = instanceClass;
478             assert(initMethod.isResolved());
479         }
480         @Override
481         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
482             return new Constructor(mt, lf, member, crackable, initMethod, instanceClass);
483         }
484         @Override
485         MethodHandle viewAsType(MethodType newType, boolean strict) {
486             assert(viewAsTypeChecks(newType, strict));
487             return new Constructor(newType, form, member, false, initMethod, instanceClass);
488         }
489     }
490 
491     /*non-public*/
492     static Object constructorMethod(Object mh) {
493         Constructor dmh = (Constructor)mh;
494         return dmh.initMethod;
495     }
496 
497     /*non-public*/
498     static Object allocateInstance(Object mh) throws InstantiationException {
499         Constructor dmh = (Constructor)mh;
500         return UNSAFE.allocateInstance(dmh.instanceClass);
501     }
502 
503     /** This subclass handles non-static field references. */
504     static final class Accessor extends DirectMethodHandle {
505         final Class<?> fieldType;
506         final int      fieldOffset;
507         private Accessor(MethodType mtype, LambdaForm form, MemberName member,
508                          boolean crackable, int fieldOffset) {
509             super(mtype, form, member, crackable);
510             this.fieldType   = member.getFieldType();
511             this.fieldOffset = fieldOffset;
512         }
513 
514         @Override Object checkCast(Object obj) {
515             return fieldType.cast(obj);
516         }
517         @Override
518         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
519             return new Accessor(mt, lf, member, crackable, fieldOffset);
520         }
521         @Override
522         MethodHandle viewAsType(MethodType newType, boolean strict) {
523             assert(viewAsTypeChecks(newType, strict));
524             return new Accessor(newType, form, member, false, fieldOffset);
525         }
526     }
527 
528     @ForceInline
529     /*non-public*/
530     static long fieldOffset(Object accessorObj) {
531         // Note: We return a long because that is what Unsafe.getObject likes.
532         // We store a plain int because it is more compact.
533         return ((Accessor)accessorObj).fieldOffset;
534     }
535 
536     @ForceInline
537     /*non-public*/
538     static Object checkBase(Object obj) {
539         // Note that the object's class has already been verified,
540         // since the parameter type of the Accessor method handle
541         // is either member.getDeclaringClass or a subclass.
542         // This was verified in DirectMethodHandle.make.
543         // Therefore, the only remaining check is for null.
544         // Since this check is *not* guaranteed by Unsafe.getInt
545         // and its siblings, we need to make an explicit one here.
546         return Objects.requireNonNull(obj);
547     }
548 
549     /** This subclass handles static field references. */
550     static final class StaticAccessor extends DirectMethodHandle {
551         private final Class<?> fieldType;
552         private final Object   staticBase;
553         private final long     staticOffset;
554 
555         private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member,
556                                boolean crackable, Object staticBase, long staticOffset) {
557             super(mtype, form, member, crackable);
558             this.fieldType    = member.getFieldType();
559             this.staticBase   = staticBase;
560             this.staticOffset = staticOffset;
561         }
562 
563         @Override Object checkCast(Object obj) {
564             return fieldType.cast(obj);
565         }
566         @Override
567         MethodHandle copyWith(MethodType mt, LambdaForm lf) {
568             return new StaticAccessor(mt, lf, member, crackable, staticBase, staticOffset);
569         }
570         @Override
571         MethodHandle viewAsType(MethodType newType, boolean strict) {
572             assert(viewAsTypeChecks(newType, strict));
573             return new StaticAccessor(newType, form, member, false, staticBase, staticOffset);
574         }
575     }
576 
577     @ForceInline
578     /*non-public*/
579     static Object nullCheck(Object obj) {
580         return Objects.requireNonNull(obj);
581     }
582 
583     @ForceInline
584     /*non-public*/
585     static Object staticBase(Object accessorObj) {
586         return ((StaticAccessor)accessorObj).staticBase;
587     }
588 
589     @ForceInline
590     /*non-public*/
591     static long staticOffset(Object accessorObj) {
592         return ((StaticAccessor)accessorObj).staticOffset;
593     }
594 
595     @ForceInline
596     /*non-public*/
597     static Object checkCast(Object mh, Object obj) {
598         return ((DirectMethodHandle) mh).checkCast(obj);
599     }
600 
601     Object checkCast(Object obj) {
602         return member.getMethodType().returnType().cast(obj);
603     }
604 
605     // Caching machinery for field accessors:
606     static final byte
607             AF_GETFIELD        = 0,
608             AF_PUTFIELD        = 1,
609             AF_GETSTATIC       = 2,
610             AF_PUTSTATIC       = 3,
611             AF_GETSTATIC_INIT  = 4,
612             AF_PUTSTATIC_INIT  = 5,
613             AF_LIMIT           = 6;
614     // Enumerate the different field kinds using Wrapper,
615     // with an extra case added for checked references.
616     static final int
617             FT_UNCHECKED_REF   = Wrapper.OBJECT.ordinal(),
618             FT_CHECKED_REF     = Wrapper.VOID.ordinal(),
619             FT_LIMIT           = Wrapper.COUNT;
620     private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) {
621         return ((formOp * FT_LIMIT * 2)
622                 + (isVolatile ? FT_LIMIT : 0)
623                 + ftypeKind);
624     }
625     @Stable
626     private static final LambdaForm[] ACCESSOR_FORMS
627             = new LambdaForm[afIndex(AF_LIMIT, false, 0)];
628     static int ftypeKind(Class<?> ftype) {
629         if (ftype.isPrimitive()) {
630             return Wrapper.forPrimitiveType(ftype).ordinal();
631         } else if (ftype.isInterface() || ftype.isAssignableFrom(Object.class)) {
632             // retyping can be done without a cast
633             return FT_UNCHECKED_REF;
634         } else {
635             return FT_CHECKED_REF;
636         }
637     }
638 
639     /**
640      * Create a LF which can access the given field.
641      * Cache and share this structure among all fields with
642      * the same basicType and refKind.
643      */
644     private static LambdaForm preparedFieldLambdaForm(MemberName m) {
645         Class<?> ftype = m.getFieldType();
646         boolean isVolatile = m.isVolatile();
647         byte formOp = switch (m.getReferenceKind()) {
648             case REF_getField  -> AF_GETFIELD;
649             case REF_putField  -> AF_PUTFIELD;
650             case REF_getStatic -> AF_GETSTATIC;
651             case REF_putStatic -> AF_PUTSTATIC;
652             default -> throw new InternalError(m.toString());
653         };
654         if (shouldBeInitialized(m)) {
655             // precompute the barrier-free version:
656             preparedFieldLambdaForm(formOp, isVolatile, ftype);
657             assert((AF_GETSTATIC_INIT - AF_GETSTATIC) ==
658                    (AF_PUTSTATIC_INIT - AF_PUTSTATIC));
659             formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC);
660         }
661         LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype);
662         assert(lform.methodType().dropParameterTypes(0, 1)
663                 .equals(m.getInvocationType().basicType()))
664                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
665         return lform;
666     }
667     private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) {
668         int ftypeKind = ftypeKind(ftype);
669         int afIndex = afIndex(formOp, isVolatile, ftypeKind);
670         LambdaForm lform = ACCESSOR_FORMS[afIndex];
671         if (lform != null)  return lform;
672         lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind);
673         ACCESSOR_FORMS[afIndex] = lform;  // don't bother with a CAS
674         return lform;
675     }
676 
677     private static final @Stable Wrapper[] ALL_WRAPPERS = Wrapper.values();
678 
679     // Names in kind may overload but differ from their basic type
680     private static Kind getFieldKind(boolean isVolatile, boolean needsInit, boolean needsCast, Wrapper wrapper) {
681         if (isVolatile) {
682             if (needsInit) {
683                 return switch (wrapper) {
684                     case BYTE -> VOLATILE_FIELD_ACCESS_INIT_B;
685                     case CHAR -> VOLATILE_FIELD_ACCESS_INIT_C;
686                     case SHORT -> VOLATILE_FIELD_ACCESS_INIT_S;
687                     case BOOLEAN -> VOLATILE_FIELD_ACCESS_INIT_Z;
688                     default -> needsCast ? VOLATILE_FIELD_ACCESS_INIT_CAST : VOLATILE_FIELD_ACCESS_INIT;
689                 };
690             } else {
691                 return switch (wrapper) {
692                     case BYTE -> VOLATILE_FIELD_ACCESS_B;
693                     case CHAR -> VOLATILE_FIELD_ACCESS_C;
694                     case SHORT -> VOLATILE_FIELD_ACCESS_S;
695                     case BOOLEAN -> VOLATILE_FIELD_ACCESS_Z;
696                     default -> needsCast ? VOLATILE_FIELD_ACCESS_CAST : VOLATILE_FIELD_ACCESS;
697                 };
698             }
699         } else {
700             if (needsInit) {
701                 return switch (wrapper) {
702                     case BYTE -> FIELD_ACCESS_INIT_B;
703                     case CHAR -> FIELD_ACCESS_INIT_C;
704                     case SHORT -> FIELD_ACCESS_INIT_S;
705                     case BOOLEAN -> FIELD_ACCESS_INIT_Z;
706                     default -> needsCast ? FIELD_ACCESS_INIT_CAST : FIELD_ACCESS_INIT;
707                 };
708             } else {
709                 return switch (wrapper) {
710                     case BYTE -> FIELD_ACCESS_B;
711                     case CHAR -> FIELD_ACCESS_C;
712                     case SHORT -> FIELD_ACCESS_S;
713                     case BOOLEAN -> FIELD_ACCESS_Z;
714                     default -> needsCast ? FIELD_ACCESS_CAST : FIELD_ACCESS;
715                 };
716             }
717         }
718     }
719 
720     private static String unsafeMethodName(boolean isGetter, boolean isVolatile, Wrapper wrapper) {
721         var name = switch (wrapper) {
722             case BOOLEAN -> "Boolean";
723             case BYTE -> "Byte";
724             case CHAR -> "Char";
725             case SHORT -> "Short";
726             case INT -> "Int";
727             case FLOAT -> "Float";
728             case LONG -> "Long";
729             case DOUBLE -> "Double";
730             case OBJECT -> "Reference";
731             case VOID -> throw new InternalError();
732         };
733         var sb = new StringBuilder(3 + name.length() + (isVolatile ? 8 : 0))
734                 .append(isGetter ? "get" : "put")
735                 .append(name);
736         if (isVolatile) {
737             sb.append("Volatile");
738         }
739         return sb.toString();
740     }
741 
742     static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
743         boolean isGetter  = (formOp & 1) == (AF_GETFIELD & 1);
744         boolean isStatic  = (formOp >= AF_GETSTATIC);
745         boolean needsInit = (formOp >= AF_GETSTATIC_INIT);
746         boolean needsCast = (ftypeKind == FT_CHECKED_REF);
747         Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]);
748         Class<?> ft = fw.primitiveType();
749         assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind);
750 
751         // getObject, putIntVolatile, etc.
752         String unsafeMethodName = unsafeMethodName(isGetter, isVolatile, fw);
753         // isGetter and isStatic is reflected in field type; basic type clash for subwords
754         Kind kind = getFieldKind(isVolatile, needsInit, needsCast, 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, unsafeMethodName, 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 = LambdaForm.create(ARG_LIMIT, names, RESULT, kind);
820 
821         if (LambdaForm.debugNames()) {
822             // add some detail to the lambdaForm debugname,
823             // significant only for debugging
824             StringBuilder nameBuilder = new StringBuilder(unsafeMethodName);
825             if (isStatic) {
826                 nameBuilder.append("Static");
827             } else {
828                 nameBuilder.append("Field");
829             }
830             if (needsCast) {
831                 nameBuilder.append("Cast");
832             }
833             if (needsInit) {
834                 nameBuilder.append("Init");
835             }
836             LambdaForm.associateWithDebugName(form, nameBuilder.toString());
837         }
838 
839         // NF_UNSAFE uses field form, avoid circular dependency in interpreter
840         form.compileToBytecode();
841         return form;
842     }
843 
844     /**
845      * Pre-initialized NamedFunctions for bootstrapping purposes.
846      */
847     static final byte NF_internalMemberName = 0,
848             NF_internalMemberNameEnsureInit = 1,
849             NF_ensureInitialized = 2,
850             NF_fieldOffset = 3,
851             NF_checkBase = 4,
852             NF_staticBase = 5,
853             NF_staticOffset = 6,
854             NF_checkCast = 7,
855             NF_allocateInstance = 8,
856             NF_constructorMethod = 9,
857             NF_UNSAFE = 10,
858             NF_checkReceiver = 11,
859             NF_LIMIT = 12;
860 
861     private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT];
862 
863     private static NamedFunction getFunction(byte func) {
864         NamedFunction nf = NFS[func];
865         if (nf != null) {
866             return nf;
867         }
868         // Each nf must be statically invocable or we get tied up in our bootstraps.
869         nf = NFS[func] = createFunction(func);
870         assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf));
871         return nf;
872     }
873 
874     private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class);
875 
876     private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class);
877 
878     private static NamedFunction createFunction(byte func) {
879         try {
880             switch (func) {
881                 case NF_internalMemberName:
882                     return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE);
883                 case NF_internalMemberNameEnsureInit:
884                     return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE);
885                 case NF_ensureInitialized:
886                     return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class));
887                 case NF_fieldOffset:
888                     return getNamedFunction("fieldOffset", LONG_OBJ_TYPE);
889                 case NF_checkBase:
890                     return getNamedFunction("checkBase", OBJ_OBJ_TYPE);
891                 case NF_staticBase:
892                     return getNamedFunction("staticBase", OBJ_OBJ_TYPE);
893                 case NF_staticOffset:
894                     return getNamedFunction("staticOffset", LONG_OBJ_TYPE);
895                 case NF_checkCast:
896                     return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class));
897                 case NF_allocateInstance:
898                     return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE);
899                 case NF_constructorMethod:
900                     return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE);
901                 case NF_UNSAFE:
902                     MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getStatic);
903                     return new NamedFunction(
904                             MemberName.getFactory().resolveOrFail(REF_getStatic, member,
905                                                                   DirectMethodHandle.class, LM_TRUSTED,
906                                                                   NoSuchFieldException.class));
907                 case NF_checkReceiver:
908                     member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual);
909                     return new NamedFunction(
910                             MemberName.getFactory().resolveOrFail(REF_invokeVirtual, member,
911                                                                   DirectMethodHandle.class, LM_TRUSTED,
912                                                                   NoSuchMethodException.class));
913                 default:
914                     throw newInternalError("Unknown function: " + func);
915             }
916         } catch (ReflectiveOperationException ex) {
917             throw newInternalError(ex);
918         }
919     }
920 
921     private static NamedFunction getNamedFunction(String name, MethodType type)
922         throws ReflectiveOperationException
923     {
924         MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic);
925         return new NamedFunction(
926                 MemberName.getFactory().resolveOrFail(REF_invokeStatic, member,
927                                                       DirectMethodHandle.class, LM_TRUSTED,
928                                                       NoSuchMethodException.class));
929     }
930 
931     static {
932         // The Holder class will contain pre-generated DirectMethodHandles resolved
933         // speculatively using MemberName.getFactory().resolveOrNull. However, that
934         // doesn't initialize the class, which subtly breaks inlining etc. By forcing
935         // initialization of the Holder class we avoid these issues.
936         UNSAFE.ensureClassInitialized(Holder.class);
937     }
938 
939     /* Placeholder class for DirectMethodHandles generated ahead of time */
940     final class Holder {}
941 }