1 /*
2 * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang.invoke;
27
28 import jdk.internal.misc.CDS;
29 import jdk.internal.value.ValueClass;
30 import jdk.internal.vm.annotation.LooselyConsistentValue;
31 import sun.invoke.util.Wrapper;
32
33 import java.lang.foreign.MemoryLayout;
34 import java.lang.reflect.Constructor;
35 import java.lang.reflect.Field;
36 import java.lang.reflect.Method;
37 import java.lang.reflect.Modifier;
38 import java.nio.ByteOrder;
39 import java.util.ArrayList;
40 import java.util.List;
41 import java.util.Objects;
42 import java.util.stream.Stream;
43
44 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
45 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_SEGMENT_FORCE_EXACT;
46 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT;
47 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
48
49 final class VarHandles {
50
51 static VarHandle makeFieldHandle(MemberName f, Class<?> refc, boolean isWriteAllowedOnFinalFields) {
52 if (!f.isStatic()) {
53 long foffset = MethodHandleNatives.objectFieldOffset(f);
54 Class<?> type = f.getFieldType();
55 if (!type.isPrimitive()) {
56 if (type.isValue()) {
57 int layout = f.getLayout();
58 boolean isAtomic = isAtomicFlat(f);
59 boolean isFlat = f.isFlat();
60 if (isFlat) {
61 if (isAtomic) {
62 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
63 ? new VarHandleFlatValues.FieldInstanceReadOnly(refc, foffset, type, f.isNullRestricted(), layout)
64 : new VarHandleFlatValues.FieldInstanceReadWrite(refc, foffset, type, f.isNullRestricted(), layout));
65 } else {
66 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
67 ? new VarHandleNonAtomicFlatValues.FieldInstanceReadOnly(refc, foffset, type, f.isNullRestricted(), layout)
68 : new VarHandleNonAtomicFlatValues.FieldInstanceReadWrite(refc, foffset, type, f.isNullRestricted(), layout));
69 }
70 } else {
71 if (isAtomic) {
72 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
73 ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type, f.isNullRestricted())
74 : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type, f.isNullRestricted()));
75 } else {
76 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
77 ? new VarHandleNonAtomicReferences.FieldInstanceReadOnly(refc, foffset, type, f.isNullRestricted())
78 : new VarHandleNonAtomicReferences.FieldInstanceReadWrite(refc, foffset, type, f.isNullRestricted()));
79 }
80 }
81 } else {
82 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
83 ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type, f.isNullRestricted())
84 : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type, f.isNullRestricted()));
85 }
86 }
87 else if (type == boolean.class) {
88 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
89 ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset)
90 : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset));
91 }
92 else if (type == byte.class) {
93 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
94 ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset)
95 : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset));
96 }
97 else if (type == short.class) {
98 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
99 ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset)
100 : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset));
101 }
102 else if (type == char.class) {
103 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
104 ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset)
105 : new VarHandleChars.FieldInstanceReadWrite(refc, foffset));
106 }
107 else if (type == int.class) {
108 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
109 ? new VarHandleInts.FieldInstanceReadOnly(refc, foffset)
110 : new VarHandleInts.FieldInstanceReadWrite(refc, foffset));
111 }
112 else if (type == long.class) {
113 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
114 ? new VarHandleLongs.FieldInstanceReadOnly(refc, foffset)
115 : new VarHandleLongs.FieldInstanceReadWrite(refc, foffset));
116 }
117 else if (type == float.class) {
118 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
119 ? new VarHandleFloats.FieldInstanceReadOnly(refc, foffset)
120 : new VarHandleFloats.FieldInstanceReadWrite(refc, foffset));
121 }
122 else if (type == double.class) {
123 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
124 ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset)
125 : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset));
126 }
127 else {
128 throw new UnsupportedOperationException();
129 }
130 }
131 else {
132 Class<?> decl = f.getDeclaringClass();
133 var vh = makeStaticFieldVarHandle(decl, f, isWriteAllowedOnFinalFields);
134 return maybeAdapt((UNSAFE.shouldBeInitialized(decl) || CDS.needsClassInitBarrier(decl))
135 ? new LazyInitializingVarHandle(vh, decl)
136 : vh);
137 }
138 }
139
140 static VarHandle makeStaticFieldVarHandle(Class<?> decl, MemberName f, boolean isWriteAllowedOnFinalFields) {
141 Object base = MethodHandleNatives.staticFieldBase(f);
142 long foffset = MethodHandleNatives.staticFieldOffset(f);
143 Class<?> type = f.getFieldType();
144 if (!type.isPrimitive()) {
145 assert !f.isFlat() : ("static field is flat in " + decl + "." + f.getName());
146 if (type.isValue()) {
147 if (isAtomicFlat(f)) {
148 return f.isFinal() && !isWriteAllowedOnFinalFields
149 ? new VarHandleReferences.FieldStaticReadOnly(decl, base, foffset, type, f.isNullRestricted())
150 : new VarHandleReferences.FieldStaticReadWrite(decl, base, foffset, type, f.isNullRestricted());
151 } else {
152 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
153 ? new VarHandleNonAtomicReferences.FieldStaticReadOnly(decl, base, foffset, type, f.isNullRestricted())
154 : new VarHandleNonAtomicReferences.FieldStaticReadWrite(decl, base, foffset, type, f.isNullRestricted()));
155 }
156 } else {
157 return f.isFinal() && !isWriteAllowedOnFinalFields
158 ? new VarHandleReferences.FieldStaticReadOnly(decl, base, foffset, type, f.isNullRestricted())
159 : new VarHandleReferences.FieldStaticReadWrite(decl, base, foffset, type, f.isNullRestricted());
160 }
161 }
162 else if (type == boolean.class) {
163 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
164 ? new VarHandleBooleans.FieldStaticReadOnly(decl, base, foffset)
165 : new VarHandleBooleans.FieldStaticReadWrite(decl, base, foffset));
166 }
167 else if (type == byte.class) {
168 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
169 ? new VarHandleBytes.FieldStaticReadOnly(decl, base, foffset)
170 : new VarHandleBytes.FieldStaticReadWrite(decl, base, foffset));
171 }
172 else if (type == short.class) {
173 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
174 ? new VarHandleShorts.FieldStaticReadOnly(decl, base, foffset)
175 : new VarHandleShorts.FieldStaticReadWrite(decl, base, foffset));
176 }
177 else if (type == char.class) {
178 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
179 ? new VarHandleChars.FieldStaticReadOnly(decl, base, foffset)
180 : new VarHandleChars.FieldStaticReadWrite(decl, base, foffset));
181 }
182 else if (type == int.class) {
183 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
184 ? new VarHandleInts.FieldStaticReadOnly(decl, base, foffset)
185 : new VarHandleInts.FieldStaticReadWrite(decl, base, foffset));
186 }
187 else if (type == long.class) {
188 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
189 ? new VarHandleLongs.FieldStaticReadOnly(decl, base, foffset)
190 : new VarHandleLongs.FieldStaticReadWrite(decl, base, foffset));
191 }
192 else if (type == float.class) {
193 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
194 ? new VarHandleFloats.FieldStaticReadOnly(decl, base, foffset)
195 : new VarHandleFloats.FieldStaticReadWrite(decl, base, foffset));
196 }
197 else if (type == double.class) {
198 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
199 ? new VarHandleDoubles.FieldStaticReadOnly(decl, base, foffset)
200 : new VarHandleDoubles.FieldStaticReadWrite(decl, base, foffset));
201 }
202 else {
203 throw new UnsupportedOperationException();
204 }
205 }
206
207 static boolean isAtomicFlat(MemberName field) {
208 boolean hasAtomicAccess = (field.getModifiers() & Modifier.VOLATILE) != 0 ||
209 !(field.isNullRestricted()) ||
210 !field.getFieldType().isAnnotationPresent(LooselyConsistentValue.class);
211 return hasAtomicAccess && !HAS_OOPS.get(field.getFieldType());
212 }
213
214 static boolean isAtomicFlat(Object[] array) {
215 Class<?> componentType = array.getClass().componentType();
216 boolean hasAtomicAccess = ValueClass.isAtomicArray(array) ||
217 !ValueClass.isNullRestrictedArray(array) ||
218 !componentType.isAnnotationPresent(LooselyConsistentValue.class);
219 return hasAtomicAccess && !HAS_OOPS.get(componentType);
220 }
221
222 static final ClassValue<Boolean> HAS_OOPS = new ClassValue<>() {
223 @Override
224 protected Boolean computeValue(Class<?> c) {
225 for (Field f : c.getDeclaredFields()) {
226 Class<?> ftype = f.getType();
227 if (UNSAFE.isFlatField(f) && HAS_OOPS.get(ftype)) {
228 return true;
229 } else if (!ftype.isPrimitive()) {
230 return true;
231 }
232 }
233 return false;
234 }
235 };
236
237 // Required by instance field handles
238 static Field getFieldFromReceiverAndOffset(Class<?> receiverType,
239 long offset,
240 Class<?> fieldType) {
241 for (Field f : receiverType.getDeclaredFields()) {
242 if (Modifier.isStatic(f.getModifiers())) continue;
243
244 if (offset == UNSAFE.objectFieldOffset(f)) {
245 assert f.getType() == fieldType;
246 return f;
247 }
248 }
249 throw new InternalError("Field not found at offset");
250 }
251
252 // Required by instance static field handles
253 static Field getStaticFieldFromBaseAndOffset(Class<?> declaringClass,
254 long offset,
255 Class<?> fieldType) {
256 for (Field f : declaringClass.getDeclaredFields()) {
257 if (!Modifier.isStatic(f.getModifiers())) continue;
258
259 if (offset == UNSAFE.staticFieldOffset(f)) {
260 assert f.getType() == fieldType;
261 return f;
262 }
263 }
264 throw new InternalError("Static field not found at offset");
265 }
266
267 // This is invoked by non-flat array var handle code when attempting to access a flat array
268 public static void checkAtomicFlatArray(Object[] array) {
269 if (!isAtomicFlat(array)) {
270 throw new IllegalArgumentException("Attempt to perform a non-plain access on a non-atomic array");
271 }
272 }
273
274 static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
275 if (!arrayClass.isArray())
276 throw new IllegalArgumentException("not an array: " + arrayClass);
277
278 Class<?> componentType = arrayClass.getComponentType();
279 if (!componentType.isPrimitive()) {
280 // Here we always return a reference array element var handle. This is because
281 // the access semantics is determined at runtime, when an actual array object is passed
282 // to the var handle. The var handle implementation will switch to use flat access
283 // primitives if it sees a flat array.
284 return maybeAdapt(new ArrayVarHandle(arrayClass));
285 }
286 else if (componentType == boolean.class) {
287 return maybeAdapt(VarHandleBooleans.Array.NON_EXACT_INSTANCE);
288 }
289 else if (componentType == byte.class) {
290 return maybeAdapt(VarHandleBytes.Array.NON_EXACT_INSTANCE);
291 }
292 else if (componentType == short.class) {
293 return maybeAdapt(VarHandleShorts.Array.NON_EXACT_INSTANCE);
294 }
295 else if (componentType == char.class) {
296 return maybeAdapt(VarHandleChars.Array.NON_EXACT_INSTANCE);
297 }
298 else if (componentType == int.class) {
299 return maybeAdapt(VarHandleInts.Array.NON_EXACT_INSTANCE);
300 }
301 else if (componentType == long.class) {
302 return maybeAdapt(VarHandleLongs.Array.NON_EXACT_INSTANCE);
303 }
304 else if (componentType == float.class) {
305 return maybeAdapt(VarHandleFloats.Array.NON_EXACT_INSTANCE);
306 }
307 else if (componentType == double.class) {
308 return maybeAdapt(VarHandleDoubles.Array.NON_EXACT_INSTANCE);
309 }
310 else {
311 throw new UnsupportedOperationException();
312 }
313 }
314
315 static VarHandle byteArrayViewHandle(Class<?> viewArrayClass,
316 boolean be) {
317 if (!viewArrayClass.isArray())
318 throw new IllegalArgumentException("not an array: " + viewArrayClass);
319
320 Class<?> viewComponentType = viewArrayClass.getComponentType();
321
322 if (viewComponentType == long.class) {
323 return maybeAdapt(new VarHandleByteArrayAsLongs.ArrayHandle(be));
324 }
325 else if (viewComponentType == int.class) {
326 return maybeAdapt(new VarHandleByteArrayAsInts.ArrayHandle(be));
327 }
328 else if (viewComponentType == short.class) {
329 return maybeAdapt(new VarHandleByteArrayAsShorts.ArrayHandle(be));
330 }
331 else if (viewComponentType == char.class) {
332 return maybeAdapt(new VarHandleByteArrayAsChars.ArrayHandle(be));
333 }
334 else if (viewComponentType == double.class) {
335 return maybeAdapt(new VarHandleByteArrayAsDoubles.ArrayHandle(be));
336 }
337 else if (viewComponentType == float.class) {
338 return maybeAdapt(new VarHandleByteArrayAsFloats.ArrayHandle(be));
339 }
340
341 throw new UnsupportedOperationException();
342 }
343
344 static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass,
345 boolean be) {
346 if (!viewArrayClass.isArray())
347 throw new IllegalArgumentException("not an array: " + viewArrayClass);
348
349 Class<?> viewComponentType = viewArrayClass.getComponentType();
350
351 if (viewComponentType == long.class) {
352 return maybeAdapt(new VarHandleByteArrayAsLongs.ByteBufferHandle(be));
353 }
354 else if (viewComponentType == int.class) {
355 return maybeAdapt(new VarHandleByteArrayAsInts.ByteBufferHandle(be));
356 }
357 else if (viewComponentType == short.class) {
358 return maybeAdapt(new VarHandleByteArrayAsShorts.ByteBufferHandle(be));
359 }
360 else if (viewComponentType == char.class) {
361 return maybeAdapt(new VarHandleByteArrayAsChars.ByteBufferHandle(be));
362 }
363 else if (viewComponentType == double.class) {
364 return maybeAdapt(new VarHandleByteArrayAsDoubles.ByteBufferHandle(be));
365 }
366 else if (viewComponentType == float.class) {
367 return maybeAdapt(new VarHandleByteArrayAsFloats.ByteBufferHandle(be));
368 }
369
370 throw new UnsupportedOperationException();
371 }
372
373 /**
374 * Creates a memory segment view var handle accessing a {@code carrier} element. It has access coordinates
375 * {@code (MS, long)} if {@code constantOffset}, {@code (MS, long, (validated) long)} otherwise.
376 * <p>
377 * The resulting var handle will take a memory segment as first argument (the segment to be dereferenced),
378 * and a {@code long} as second argument (the offset into the segment). Both arguments are checked.
379 * <p>
380 * If {@code constantOffset == false}, the resulting var handle will take a third pre-validated additional
381 * offset instead of the given fixed {@code offset}, and caller must ensure that passed additional offset,
382 * either to the handle (such as computing through method handles) or as fixed {@code offset} here, is valid.
383 *
384 * @param carrier the Java carrier type of the element
385 * @param enclosing the enclosing layout to perform bound and alignment checks against
386 * @param alignmentMask alignment of this accessed element in the enclosing layout
387 * @param constantOffset if access path has a constant offset value, i.e. it has no strides
388 * @param offset the offset value, if the offset is constant
389 * @param byteOrder the byte order
390 * @return the created var handle
391 */
392 static VarHandle memorySegmentViewHandle(Class<?> carrier, MemoryLayout enclosing, long alignmentMask,
393 boolean constantOffset, long offset, ByteOrder byteOrder) {
394 if (!carrier.isPrimitive() || carrier == void.class) {
395 throw new IllegalArgumentException("Invalid carrier: " + carrier.getName());
396 }
397 boolean be = byteOrder == ByteOrder.BIG_ENDIAN;
398 boolean exact = VAR_HANDLE_SEGMENT_FORCE_EXACT;
399
400 // All carrier types must persist across MethodType erasure
401 VarForm form;
402 if (carrier == byte.class) {
403 form = VarHandleSegmentAsBytes.selectForm(alignmentMask, constantOffset);
404 } else if (carrier == char.class) {
405 form = VarHandleSegmentAsChars.selectForm(alignmentMask, constantOffset);
406 } else if (carrier == short.class) {
407 form = VarHandleSegmentAsShorts.selectForm(alignmentMask, constantOffset);
408 } else if (carrier == int.class) {
409 form = VarHandleSegmentAsInts.selectForm(alignmentMask, constantOffset);
410 } else if (carrier == float.class) {
411 form = VarHandleSegmentAsFloats.selectForm(alignmentMask, constantOffset);
412 } else if (carrier == long.class) {
413 form = VarHandleSegmentAsLongs.selectForm(alignmentMask, constantOffset);
414 } else if (carrier == double.class) {
415 form = VarHandleSegmentAsDoubles.selectForm(alignmentMask, constantOffset);
416 } else if (carrier == boolean.class) {
417 form = VarHandleSegmentAsBooleans.selectForm(alignmentMask, constantOffset);
418 } else {
419 throw new IllegalStateException("Cannot get here");
420 }
421
422 return maybeAdapt(new SegmentVarHandle(form, be, enclosing, offset, exact));
423 }
424
425 private static VarHandle maybeAdapt(VarHandle target) {
426 if (!VAR_HANDLE_IDENTITY_ADAPT) return target;
427 target = filterValue(target,
428 MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType()));
429 MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET);
430 for (int i = 0 ; i < mtype.parameterCount() ; i++) {
431 target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i)));
432 }
433 return target;
434 }
435
436 public static VarHandle filterValue(VarHandle target, MethodHandle pFilterToTarget, MethodHandle pFilterFromTarget) {
437 Objects.requireNonNull(target);
438 Objects.requireNonNull(pFilterToTarget);
439 Objects.requireNonNull(pFilterFromTarget);
440 //check that from/to filters do not throw checked exceptions
441 MethodHandle filterToTarget = adaptForCheckedExceptions(pFilterToTarget);
442 MethodHandle filterFromTarget = adaptForCheckedExceptions(pFilterFromTarget);
443
444 List<Class<?>> newCoordinates = new ArrayList<>();
445 List<Class<?>> additionalCoordinates = new ArrayList<>();
446 newCoordinates.addAll(target.coordinateTypes());
447
448 //check that from/to filters have right signatures
449 if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) {
450 throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type());
451 } else if (filterFromTarget.type().parameterCount() < 1) {
452 throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type());
453 } else if (filterToTarget.type().parameterCount() < 1) {
454 throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type());
455 } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() ||
456 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) {
457 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
458 } else if (target.varType() != filterFromTarget.type().lastParameterType()) {
459 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType());
460 } else if (target.varType() != filterToTarget.type().returnType()) {
461 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType());
462 } else if (filterFromTarget.type().parameterCount() > 1) {
463 for (int i = 0 ; i < filterFromTarget.type().parameterCount() - 1 ; i++) {
464 if (filterFromTarget.type().parameterType(i) != filterToTarget.type().parameterType(i)) {
465 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
466 } else {
467 newCoordinates.add(filterFromTarget.type().parameterType(i));
468 additionalCoordinates.add((filterFromTarget.type().parameterType(i)));
469 }
470 }
471 }
472
473 return new IndirectVarHandle(target, filterFromTarget.type().returnType(), newCoordinates.toArray(new Class<?>[0]),
474 (mode, modeHandle) -> {
475 int lastParameterPos = modeHandle.type().parameterCount() - 1;
476 return switch (mode.at) {
477 case GET -> MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
478 case SET -> MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
479 case GET_AND_UPDATE -> {
480 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
481 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
482 if (additionalCoordinates.size() > 0) {
483 res = joinDuplicateArgs(res, lastParameterPos,
484 lastParameterPos + additionalCoordinates.size() + 1,
485 additionalCoordinates.size());
486 }
487 yield res;
488 }
489 case COMPARE_AND_EXCHANGE -> {
490 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
491 adapter = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
492 if (additionalCoordinates.size() > 0) {
493 adapter = joinDuplicateArgs(adapter, lastParameterPos,
494 lastParameterPos + additionalCoordinates.size() + 1,
495 additionalCoordinates.size());
496 }
497 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
498 if (additionalCoordinates.size() > 0) {
499 res = joinDuplicateArgs(res, lastParameterPos - 1,
500 lastParameterPos + additionalCoordinates.size(),
501 additionalCoordinates.size());
502 }
503 yield res;
504 }
505 case COMPARE_AND_SET -> {
506 MethodHandle adapter = MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
507 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
508 if (additionalCoordinates.size() > 0) {
509 res = joinDuplicateArgs(res, lastParameterPos - 1,
510 lastParameterPos + additionalCoordinates.size(),
511 additionalCoordinates.size());
512 }
513 yield res;
514 }
515 };
516 });
517 }
518
519 private static MethodHandle joinDuplicateArgs(MethodHandle handle, int originalStart, int dropStart, int length) {
520 int[] perms = new int[handle.type().parameterCount()];
521 for (int i = 0 ; i < dropStart; i++) {
522 perms[i] = i;
523 }
524 for (int i = 0 ; i < length ; i++) {
525 perms[dropStart + i] = originalStart + i;
526 }
527 for (int i = dropStart + length ; i < perms.length ; i++) {
528 perms[i] = i - length;
529 }
530 return MethodHandles.permuteArguments(handle,
531 handle.type().dropParameterTypes(dropStart, dropStart + length),
532 perms);
533 }
534
535 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
536 Objects.requireNonNull(target);
537 Objects.requireNonNull(filters);
538
539 List<Class<?>> targetCoordinates = target.coordinateTypes();
540 if (pos < 0 || pos >= targetCoordinates.size()) {
541 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
542 } else if (pos + filters.length > targetCoordinates.size()) {
543 throw new IllegalArgumentException("Too many filters");
544 }
545
546 if (filters.length == 0) return target;
547
548 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
549 for (int i = 0 ; i < filters.length ; i++) {
550 MethodHandle filter = Objects.requireNonNull(filters[i]);
551 filter = adaptForCheckedExceptions(filter);
552 MethodType filterType = filter.type();
553 if (filterType.parameterCount() != 1) {
554 throw newIllegalArgumentException("Invalid filter type " + filterType);
555 } else if (newCoordinates.get(pos + i) != filterType.returnType()) {
556 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i));
557 }
558 newCoordinates.set(pos + i, filters[i].type().parameterType(0));
559 }
560
561 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
562 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters));
563 }
564
565 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
566 Objects.requireNonNull(target);
567 Objects.requireNonNull(values);
568
569 List<Class<?>> targetCoordinates = target.coordinateTypes();
570 if (pos < 0 || pos >= targetCoordinates.size()) {
571 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
572 } else if (pos + values.length > targetCoordinates.size()) {
573 throw new IllegalArgumentException("Too many values");
574 }
575
576 if (values.length == 0) return target;
577
578 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
579 for (int i = 0 ; i < values.length ; i++) {
580 Class<?> pt = newCoordinates.get(pos);
581 if (pt.isPrimitive()) {
582 Wrapper w = Wrapper.forPrimitiveType(pt);
583 w.convert(values[i], pt);
584 } else {
585 pt.cast(values[i]);
586 }
587 newCoordinates.remove(pos);
588 }
589
590 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
591 (mode, modeHandle) -> MethodHandles.insertArguments(modeHandle, 1 + pos, values));
592 }
593
594 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
595 Objects.requireNonNull(target);
596 Objects.requireNonNull(newCoordinates);
597 Objects.requireNonNull(reorder);
598
599 List<Class<?>> targetCoordinates = target.coordinateTypes();
600 MethodHandles.permuteArgumentChecks(reorder,
601 MethodType.methodType(void.class, newCoordinates),
602 MethodType.methodType(void.class, targetCoordinates));
603
604 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
605 (mode, modeHandle) ->
606 MethodHandles.permuteArguments(modeHandle,
607 methodTypeFor(mode.at, modeHandle.type(), targetCoordinates, newCoordinates),
608 reorderArrayFor(mode.at, newCoordinates, reorder)));
609 }
610
611 private static int numTrailingArgs(VarHandle.AccessType at) {
612 return switch (at) {
613 case GET -> 0;
614 case GET_AND_UPDATE, SET -> 1;
615 case COMPARE_AND_SET, COMPARE_AND_EXCHANGE -> 2;
616 };
617 }
618
619 private static int[] reorderArrayFor(VarHandle.AccessType at, List<Class<?>> newCoordinates, int[] reorder) {
620 int numTrailingArgs = numTrailingArgs(at);
621 int[] adjustedReorder = new int[reorder.length + 1 + numTrailingArgs];
622 adjustedReorder[0] = 0;
623 for (int i = 0 ; i < reorder.length ; i++) {
624 adjustedReorder[i + 1] = reorder[i] + 1;
625 }
626 for (int i = 0 ; i < numTrailingArgs ; i++) {
627 adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1;
628 }
629 return adjustedReorder;
630 }
631
632 private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) {
633 int numTrailingArgs = numTrailingArgs(at);
634 MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0));
635 adjustedType = adjustedType.appendParameterTypes(newCoordinates);
636 for (int i = 0 ; i < numTrailingArgs ; i++) {
637 adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i));
638 }
639 return adjustedType;
640 }
641
642 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle pFilter) {
643 Objects.requireNonNull(target);
644 Objects.requireNonNull(pFilter);
645 MethodHandle filter = adaptForCheckedExceptions(pFilter);
646
647 List<Class<?>> targetCoordinates = target.coordinateTypes();
648 if (pos < 0 || pos >= targetCoordinates.size()) {
649 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
650 } else if (filter.type().returnType() != void.class && filter.type().returnType() != targetCoordinates.get(pos)) {
651 throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos));
652 }
653
654 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
655 if (filter.type().returnType() != void.class) {
656 newCoordinates.remove(pos);
657 }
658 newCoordinates.addAll(pos, filter.type().parameterList());
659
660 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
661 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter));
662 }
663
664 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
665 Objects.requireNonNull(target);
666 Objects.requireNonNull(valueTypes);
667
668 List<Class<?>> targetCoordinates = target.coordinateTypes();
669 if (pos < 0 || pos > targetCoordinates.size()) {
670 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
671 }
672
673 if (valueTypes.length == 0) return target;
674
675 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
676 newCoordinates.addAll(pos, List.of(valueTypes));
677
678 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
679 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
680 }
681
682 private static MethodHandle adaptForCheckedExceptions(MethodHandle target) {
683 Class<?>[] exceptionTypes = exceptionTypes(target);
684 if (exceptionTypes != null) { // exceptions known
685 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
686 throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
687 }
688 return target; // no adaptation needed
689 } else {
690 MethodHandle handler = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_VarHandles_handleCheckedExceptions);
691 MethodHandle zero = MethodHandles.zero(target.type().returnType()); // dead branch
692 handler = MethodHandles.collectArguments(zero, 0, handler);
693 return MethodHandles.catchException(target, Throwable.class, handler);
694 }
695 }
696
697 static void handleCheckedExceptions(Throwable throwable) throws Throwable {
698 if (isCheckedException(throwable.getClass())) {
699 throw new IllegalStateException("Adapter handle threw checked exception", throwable);
700 }
701 throw throwable;
702 }
703
704 static Class<?>[] exceptionTypes(MethodHandle handle) {
705 if (handle instanceof DirectMethodHandle directHandle) {
706 byte refKind = directHandle.member.getReferenceKind();
707 MethodHandleInfo info = new InfoFromMemberName(
708 MethodHandles.Lookup.IMPL_LOOKUP,
709 directHandle.member,
710 refKind);
711 if (MethodHandleNatives.refKindIsMethod(refKind)) {
712 return info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
713 .getExceptionTypes();
714 } else if (MethodHandleNatives.refKindIsField(refKind)) {
715 return new Class<?>[0];
716 } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
717 return info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
718 .getExceptionTypes();
719 } else {
720 throw new AssertionError("Cannot get here");
721 }
722 } else if (handle instanceof DelegatingMethodHandle delegatingMh) {
723 return exceptionTypes(delegatingMh.getTarget());
724 } else if (handle instanceof NativeMethodHandle) {
725 return new Class<?>[0];
726 }
727
728 assert handle instanceof BoundMethodHandle : "Unexpected handle type: " + handle;
729 // unknown
730 return null;
731 }
732
733 private static boolean isCheckedException(Class<?> clazz) {
734 return Throwable.class.isAssignableFrom(clazz) &&
735 !RuntimeException.class.isAssignableFrom(clazz) &&
736 !Error.class.isAssignableFrom(clazz);
737 }
738 }