< prev index next >

src/java.base/share/classes/java/lang/invoke/VarHandles.java

Print this page

 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 sun.invoke.util.Wrapper;
 29 
 30 import java.lang.reflect.Constructor;
 31 import java.lang.reflect.Field;
 32 import java.lang.reflect.Method;
 33 import java.lang.reflect.Modifier;
 34 import java.lang.reflect.Parameter;
 35 import java.nio.ByteOrder;
 36 import java.util.ArrayList;
 37 import java.util.LinkedHashMap;
 38 import java.util.List;
 39 import java.util.Map;
 40 import java.util.Objects;
 41 import java.util.concurrent.ConcurrentHashMap;
 42 import java.util.concurrent.ConcurrentMap;
 43 import java.util.stream.Stream;
 44 
 45 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
 46 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT;
 47 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
 48 import static java.util.stream.Collectors.joining;
 49 import static java.util.stream.Collectors.toList;
 50 
 51 final class VarHandles {
 52 
 53     static ClassValue<ConcurrentMap<Integer, MethodHandle>> ADDRESS_FACTORIES = new ClassValue<>() {
 54         @Override
 55         protected ConcurrentMap<Integer, MethodHandle> computeValue(Class<?> type) {
 56             return new ConcurrentHashMap<>();
 57         }
 58     };
 59 
 60     static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) {
 61         if (!f.isStatic()) {
 62             long foffset = MethodHandleNatives.objectFieldOffset(f);
 63             if (!type.isPrimitive()) {
 64                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields





 65                        ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type)
 66                        : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type));

 67             }
 68             else if (type == boolean.class) {
 69                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 70                        ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset)
 71                        : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset));
 72             }
 73             else if (type == byte.class) {
 74                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 75                        ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset)
 76                        : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset));
 77             }
 78             else if (type == short.class) {
 79                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 80                        ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset)
 81                        : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset));
 82             }
 83             else if (type == char.class) {
 84                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 85                        ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset)
 86                        : new VarHandleChars.FieldInstanceReadWrite(refc, foffset));

105                        ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset)
106                        : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset));
107             }
108             else {
109                 throw new UnsupportedOperationException();
110             }
111         }
112         else {
113             // TODO This is not lazy on first invocation
114             // and might cause some circular initialization issues
115 
116             // Replace with something similar to direct method handles
117             // where a barrier is used then elided after use
118 
119             if (UNSAFE.shouldBeInitialized(refc))
120                 UNSAFE.ensureClassInitialized(refc);
121 
122             Object base = MethodHandleNatives.staticFieldBase(f);
123             long foffset = MethodHandleNatives.staticFieldOffset(f);
124             if (!type.isPrimitive()) {
125                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
126                        ? new VarHandleReferences.FieldStaticReadOnly(base, foffset, type)
127                        : new VarHandleReferences.FieldStaticReadWrite(base, foffset, type));






128             }
129             else if (type == boolean.class) {
130                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
131                        ? new VarHandleBooleans.FieldStaticReadOnly(base, foffset)
132                        : new VarHandleBooleans.FieldStaticReadWrite(base, foffset));
133             }
134             else if (type == byte.class) {
135                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
136                        ? new VarHandleBytes.FieldStaticReadOnly(base, foffset)
137                        : new VarHandleBytes.FieldStaticReadWrite(base, foffset));
138             }
139             else if (type == short.class) {
140                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
141                        ? new VarHandleShorts.FieldStaticReadOnly(base, foffset)
142                        : new VarHandleShorts.FieldStaticReadWrite(base, foffset));
143             }
144             else if (type == char.class) {
145                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
146                        ? new VarHandleChars.FieldStaticReadOnly(base, foffset)
147                        : new VarHandleChars.FieldStaticReadWrite(base, foffset));

198 
199             if (offset == UNSAFE.staticFieldOffset(f)) {
200                 assert f.getType() == fieldType;
201                 return f;
202             }
203         }
204         throw new InternalError("Static field not found at offset");
205     }
206 
207     static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
208         if (!arrayClass.isArray())
209             throw new IllegalArgumentException("not an array: " + arrayClass);
210 
211         Class<?> componentType = arrayClass.getComponentType();
212 
213         int aoffset = UNSAFE.arrayBaseOffset(arrayClass);
214         int ascale = UNSAFE.arrayIndexScale(arrayClass);
215         int ashift = 31 - Integer.numberOfLeadingZeros(ascale);
216 
217         if (!componentType.isPrimitive()) {
218             return maybeAdapt(new VarHandleReferences.Array(aoffset, ashift, arrayClass));






219         }
220         else if (componentType == boolean.class) {
221             return maybeAdapt(new VarHandleBooleans.Array(aoffset, ashift));
222         }
223         else if (componentType == byte.class) {
224             return maybeAdapt(new VarHandleBytes.Array(aoffset, ashift));
225         }
226         else if (componentType == short.class) {
227             return maybeAdapt(new VarHandleShorts.Array(aoffset, ashift));
228         }
229         else if (componentType == char.class) {
230             return maybeAdapt(new VarHandleChars.Array(aoffset, ashift));
231         }
232         else if (componentType == int.class) {
233             return maybeAdapt(new VarHandleInts.Array(aoffset, ashift));
234         }
235         else if (componentType == long.class) {
236             return maybeAdapt(new VarHandleLongs.Array(aoffset, ashift));
237         }
238         else if (componentType == float.class) {

600         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
601         newCoordinates.addAll(pos, List.of(valueTypes));
602 
603         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
604                 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
605     }
606 
607     private static void noCheckedExceptions(MethodHandle handle) {
608         if (handle instanceof DirectMethodHandle directHandle) {
609             byte refKind = directHandle.member.getReferenceKind();
610             MethodHandleInfo info = new InfoFromMemberName(
611                     MethodHandles.Lookup.IMPL_LOOKUP,
612                     directHandle.member,
613                     refKind);
614             final Class<?>[] exceptionTypes;
615             if (MethodHandleNatives.refKindIsMethod(refKind)) {
616                 exceptionTypes = info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
617                         .getExceptionTypes();
618             } else if (MethodHandleNatives.refKindIsField(refKind)) {
619                 exceptionTypes = null;
620             } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
621                 exceptionTypes = info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
622                         .getExceptionTypes();
623             } else {
624                 throw new AssertionError("Cannot get here");
625             }
626             if (exceptionTypes != null) {
627                 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
628                     throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
629                 }
630             }
631         } else if (handle instanceof DelegatingMethodHandle) {
632             noCheckedExceptions(((DelegatingMethodHandle)handle).getTarget());
633         } else {
634             //bound
635             BoundMethodHandle boundHandle = (BoundMethodHandle)handle;
636             for (int i = 0 ; i < boundHandle.fieldCount() ; i++) {
637                 Object arg = boundHandle.arg(i);
638                 if (arg instanceof MethodHandle){
639                     noCheckedExceptions((MethodHandle) arg);
640                 }

 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 sun.invoke.util.Wrapper;
 29 
 30 import java.lang.reflect.Constructor;
 31 import java.lang.reflect.Field;
 32 import java.lang.reflect.Method;
 33 import java.lang.reflect.Modifier;

 34 import java.nio.ByteOrder;
 35 import java.util.ArrayList;

 36 import java.util.List;

 37 import java.util.Objects;
 38 import java.util.concurrent.ConcurrentHashMap;
 39 import java.util.concurrent.ConcurrentMap;
 40 import java.util.stream.Stream;
 41 
 42 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
 43 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT;
 44 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
 45 import static java.util.stream.Collectors.joining;

 46 
 47 final class VarHandles {
 48 
 49     static ClassValue<ConcurrentMap<Integer, MethodHandle>> ADDRESS_FACTORIES = new ClassValue<>() {
 50         @Override
 51         protected ConcurrentMap<Integer, MethodHandle> computeValue(Class<?> type) {
 52             return new ConcurrentHashMap<>();
 53         }
 54     };
 55 
 56     static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) {
 57         if (!f.isStatic()) {
 58             long foffset = MethodHandleNatives.objectFieldOffset(f);
 59             if (!type.isPrimitive()) {
 60                 if (f.isFlattened()) {
 61                     return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 62                         ? new VarHandleValues.FieldInstanceReadOnly(refc, foffset, type)
 63                         : new VarHandleValues.FieldInstanceReadWrite(refc, foffset, type));
 64                 } else {
 65                     return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 66                        ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type)
 67                        : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type));
 68                 }
 69             }
 70             else if (type == boolean.class) {
 71                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 72                        ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset)
 73                        : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset));
 74             }
 75             else if (type == byte.class) {
 76                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 77                        ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset)
 78                        : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset));
 79             }
 80             else if (type == short.class) {
 81                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 82                        ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset)
 83                        : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset));
 84             }
 85             else if (type == char.class) {
 86                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
 87                        ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset)
 88                        : new VarHandleChars.FieldInstanceReadWrite(refc, foffset));

107                        ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset)
108                        : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset));
109             }
110             else {
111                 throw new UnsupportedOperationException();
112             }
113         }
114         else {
115             // TODO This is not lazy on first invocation
116             // and might cause some circular initialization issues
117 
118             // Replace with something similar to direct method handles
119             // where a barrier is used then elided after use
120 
121             if (UNSAFE.shouldBeInitialized(refc))
122                 UNSAFE.ensureClassInitialized(refc);
123 
124             Object base = MethodHandleNatives.staticFieldBase(f);
125             long foffset = MethodHandleNatives.staticFieldOffset(f);
126             if (!type.isPrimitive()) {
127                 if (f.isFlattened()) {
128                     return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
129                             ? new VarHandleValues.FieldStaticReadOnly(refc, foffset, type)
130                             : new VarHandleValues.FieldStaticReadWrite(refc, foffset, type));
131                 } else {
132                     return f.isFinal() && !isWriteAllowedOnFinalFields
133                             ? new VarHandleReferences.FieldStaticReadOnly(base, foffset, type)
134                             : new VarHandleReferences.FieldStaticReadWrite(base, foffset, type);
135                 }
136             }
137             else if (type == boolean.class) {
138                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
139                        ? new VarHandleBooleans.FieldStaticReadOnly(base, foffset)
140                        : new VarHandleBooleans.FieldStaticReadWrite(base, foffset));
141             }
142             else if (type == byte.class) {
143                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
144                        ? new VarHandleBytes.FieldStaticReadOnly(base, foffset)
145                        : new VarHandleBytes.FieldStaticReadWrite(base, foffset));
146             }
147             else if (type == short.class) {
148                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
149                        ? new VarHandleShorts.FieldStaticReadOnly(base, foffset)
150                        : new VarHandleShorts.FieldStaticReadWrite(base, foffset));
151             }
152             else if (type == char.class) {
153                 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
154                        ? new VarHandleChars.FieldStaticReadOnly(base, foffset)
155                        : new VarHandleChars.FieldStaticReadWrite(base, foffset));

206 
207             if (offset == UNSAFE.staticFieldOffset(f)) {
208                 assert f.getType() == fieldType;
209                 return f;
210             }
211         }
212         throw new InternalError("Static field not found at offset");
213     }
214 
215     static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
216         if (!arrayClass.isArray())
217             throw new IllegalArgumentException("not an array: " + arrayClass);
218 
219         Class<?> componentType = arrayClass.getComponentType();
220 
221         int aoffset = UNSAFE.arrayBaseOffset(arrayClass);
222         int ascale = UNSAFE.arrayIndexScale(arrayClass);
223         int ashift = 31 - Integer.numberOfLeadingZeros(ascale);
224 
225         if (!componentType.isPrimitive()) {
226             // the redundant componentType.isValue() check is there to
227             // minimize the performance impact to non-value array.
228             // It should be removed when Unsafe::isFlattenedArray is intrinsified.
229 
230             return maybeAdapt(componentType.isValueType() && UNSAFE.isFlattenedArray(arrayClass)
231                 ? new VarHandleValues.Array(aoffset, ashift, arrayClass)
232                 : new VarHandleReferences.Array(aoffset, ashift, arrayClass));
233         }
234         else if (componentType == boolean.class) {
235             return maybeAdapt(new VarHandleBooleans.Array(aoffset, ashift));
236         }
237         else if (componentType == byte.class) {
238             return maybeAdapt(new VarHandleBytes.Array(aoffset, ashift));
239         }
240         else if (componentType == short.class) {
241             return maybeAdapt(new VarHandleShorts.Array(aoffset, ashift));
242         }
243         else if (componentType == char.class) {
244             return maybeAdapt(new VarHandleChars.Array(aoffset, ashift));
245         }
246         else if (componentType == int.class) {
247             return maybeAdapt(new VarHandleInts.Array(aoffset, ashift));
248         }
249         else if (componentType == long.class) {
250             return maybeAdapt(new VarHandleLongs.Array(aoffset, ashift));
251         }
252         else if (componentType == float.class) {

614         List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
615         newCoordinates.addAll(pos, List.of(valueTypes));
616 
617         return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
618                 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
619     }
620 
621     private static void noCheckedExceptions(MethodHandle handle) {
622         if (handle instanceof DirectMethodHandle directHandle) {
623             byte refKind = directHandle.member.getReferenceKind();
624             MethodHandleInfo info = new InfoFromMemberName(
625                     MethodHandles.Lookup.IMPL_LOOKUP,
626                     directHandle.member,
627                     refKind);
628             final Class<?>[] exceptionTypes;
629             if (MethodHandleNatives.refKindIsMethod(refKind)) {
630                 exceptionTypes = info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
631                         .getExceptionTypes();
632             } else if (MethodHandleNatives.refKindIsField(refKind)) {
633                 exceptionTypes = null;
634             } else if (MethodHandleNatives.refKindIsObjectConstructor(refKind)) {
635                 exceptionTypes = info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
636                         .getExceptionTypes();
637             } else {
638                 throw new AssertionError("Cannot get here");
639             }
640             if (exceptionTypes != null) {
641                 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
642                     throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
643                 }
644             }
645         } else if (handle instanceof DelegatingMethodHandle) {
646             noCheckedExceptions(((DelegatingMethodHandle)handle).getTarget());
647         } else {
648             //bound
649             BoundMethodHandle boundHandle = (BoundMethodHandle)handle;
650             for (int i = 0 ; i < boundHandle.fieldCount() ; i++) {
651                 Object arg = boundHandle.arg(i);
652                 if (arg instanceof MethodHandle){
653                     noCheckedExceptions((MethodHandle) arg);
654                 }
< prev index next >