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