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