1 /*
2 * Copyright (c) 2014, 2026, 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 (ValueClass.isConcreteValueClass(type)) {
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 (ValueClass.isConcreteValueClass(type)) {
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 && ValueClass.hasBinaryPayload(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 && ValueClass.hasBinaryPayload(componentType);
220 }
221
222 // Required by instance field handles
223 static Field getFieldFromReceiverAndOffset(Class<?> receiverType,
224 long offset,
225 Class<?> fieldType) {
226 // The receiver may be a referenced class different from the declaring class
227 for (var declaringClass = receiverType; declaringClass != null; declaringClass = declaringClass.getSuperclass()) {
228 for (Field f : declaringClass.getDeclaredFields()) {
229 if (Modifier.isStatic(f.getModifiers())) continue;
230
231 if (offset == UNSAFE.objectFieldOffset(f)) {
232 assert f.getType() == fieldType;
233 return f;
234 }
235 }
236 }
237 throw new InternalError("Field not found at offset");
238 }
239
240 // Required by instance static field handles
241 static Field getStaticFieldFromBaseAndOffset(Class<?> declaringClass,
242 long offset,
243 Class<?> fieldType) {
244 for (Field f : declaringClass.getDeclaredFields()) {
245 if (!Modifier.isStatic(f.getModifiers())) continue;
246
247 if (offset == UNSAFE.staticFieldOffset(f)) {
248 assert f.getType() == fieldType;
249 return f;
250 }
251 }
252 throw new InternalError("Static field not found at offset");
253 }
254
255 // This is invoked by non-flat array var handle code when attempting to access a flat array
256 public static void checkAtomicFlatArray(Object[] array) {
257 if (!isAtomicFlat(array)) {
258 throw new IllegalArgumentException("Attempt to perform a non-plain access on a non-atomic array");
259 }
260 }
261
262 static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
263 if (!arrayClass.isArray())
264 throw new IllegalArgumentException("not an array: " + arrayClass);
265
266 Class<?> componentType = arrayClass.getComponentType();
267 if (!componentType.isPrimitive()) {
268 // Here we always return a reference array element var handle. This is because
269 // the access semantics is determined at runtime, when an actual array object is passed
270 // to the var handle. The var handle implementation will switch to use flat access
271 // primitives if it sees a flat array.
272 return maybeAdapt(new ArrayVarHandle(arrayClass));
273 }
274 else if (componentType == boolean.class) {
275 return maybeAdapt(VarHandleBooleans.Array.NON_EXACT_INSTANCE);
276 }
277 else if (componentType == byte.class) {
278 return maybeAdapt(VarHandleBytes.Array.NON_EXACT_INSTANCE);
279 }
280 else if (componentType == short.class) {
281 return maybeAdapt(VarHandleShorts.Array.NON_EXACT_INSTANCE);
282 }
283 else if (componentType == char.class) {
284 return maybeAdapt(VarHandleChars.Array.NON_EXACT_INSTANCE);
285 }
286 else if (componentType == int.class) {
287 return maybeAdapt(VarHandleInts.Array.NON_EXACT_INSTANCE);
288 }
289 else if (componentType == long.class) {
290 return maybeAdapt(VarHandleLongs.Array.NON_EXACT_INSTANCE);
291 }
292 else if (componentType == float.class) {
293 return maybeAdapt(VarHandleFloats.Array.NON_EXACT_INSTANCE);
294 }
295 else if (componentType == double.class) {
296 return maybeAdapt(VarHandleDoubles.Array.NON_EXACT_INSTANCE);
297 }
298 else {
299 throw new UnsupportedOperationException();
300 }
301 }
302
303 static VarHandle byteArrayViewHandle(Class<?> viewArrayClass,
304 boolean be) {
305 if (!viewArrayClass.isArray())
306 throw new IllegalArgumentException("not an array: " + viewArrayClass);
307
308 Class<?> viewComponentType = viewArrayClass.getComponentType();
309
310 if (viewComponentType == long.class) {
311 return maybeAdapt(new VarHandleByteArrayAsLongs.ArrayHandle(be));
312 }
313 else if (viewComponentType == int.class) {
314 return maybeAdapt(new VarHandleByteArrayAsInts.ArrayHandle(be));
315 }
316 else if (viewComponentType == short.class) {
317 return maybeAdapt(new VarHandleByteArrayAsShorts.ArrayHandle(be));
318 }
319 else if (viewComponentType == char.class) {
320 return maybeAdapt(new VarHandleByteArrayAsChars.ArrayHandle(be));
321 }
322 else if (viewComponentType == double.class) {
323 return maybeAdapt(new VarHandleByteArrayAsDoubles.ArrayHandle(be));
324 }
325 else if (viewComponentType == float.class) {
326 return maybeAdapt(new VarHandleByteArrayAsFloats.ArrayHandle(be));
327 }
328
329 throw new UnsupportedOperationException();
330 }
331
332 static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass,
333 boolean be) {
334 if (!viewArrayClass.isArray())
335 throw new IllegalArgumentException("not an array: " + viewArrayClass);
336
337 Class<?> viewComponentType = viewArrayClass.getComponentType();
338
339 if (viewComponentType == long.class) {
340 return maybeAdapt(new VarHandleByteArrayAsLongs.ByteBufferHandle(be));
341 }
342 else if (viewComponentType == int.class) {
343 return maybeAdapt(new VarHandleByteArrayAsInts.ByteBufferHandle(be));
344 }
345 else if (viewComponentType == short.class) {
346 return maybeAdapt(new VarHandleByteArrayAsShorts.ByteBufferHandle(be));
347 }
348 else if (viewComponentType == char.class) {
349 return maybeAdapt(new VarHandleByteArrayAsChars.ByteBufferHandle(be));
350 }
351 else if (viewComponentType == double.class) {
352 return maybeAdapt(new VarHandleByteArrayAsDoubles.ByteBufferHandle(be));
353 }
354 else if (viewComponentType == float.class) {
355 return maybeAdapt(new VarHandleByteArrayAsFloats.ByteBufferHandle(be));
356 }
357
358 throw new UnsupportedOperationException();
359 }
360
361 /**
362 * Creates a memory segment view var handle accessing a {@code carrier} element. It has access coordinates
363 * {@code (MS, long)} if {@code constantOffset}, {@code (MS, long, (validated) long)} otherwise.
364 * <p>
365 * The resulting var handle will take a memory segment as first argument (the segment to be dereferenced),
366 * and a {@code long} as second argument (the offset into the segment). Both arguments are checked.
367 * <p>
368 * If {@code constantOffset == false}, the resulting var handle will take a third pre-validated additional
369 * offset instead of the given fixed {@code offset}, and caller must ensure that passed additional offset,
370 * either to the handle (such as computing through method handles) or as fixed {@code offset} here, is valid.
371 *
372 * @param carrier the Java carrier type of the element
373 * @param enclosing the enclosing layout to perform bound and alignment checks against
374 * @param alignmentMask alignment of this accessed element in the enclosing layout
375 * @param constantOffset if access path has a constant offset value, i.e. it has no strides
376 * @param offset the offset value, if the offset is constant
377 * @param byteOrder the byte order
378 * @return the created var handle
379 */
380 static VarHandle memorySegmentViewHandle(Class<?> carrier, MemoryLayout enclosing, long alignmentMask,
381 boolean constantOffset, long offset, ByteOrder byteOrder) {
382 if (!carrier.isPrimitive() || carrier == void.class) {
383 throw new IllegalArgumentException("Invalid carrier: " + carrier.getName());
384 }
385 boolean be = byteOrder == ByteOrder.BIG_ENDIAN;
386 boolean exact = VAR_HANDLE_SEGMENT_FORCE_EXACT;
387
388 // All carrier types must persist across MethodType erasure
389 VarForm form;
390 if (carrier == byte.class) {
391 form = VarHandleSegmentAsBytes.selectForm(alignmentMask, constantOffset);
392 } else if (carrier == char.class) {
393 form = VarHandleSegmentAsChars.selectForm(alignmentMask, constantOffset);
394 } else if (carrier == short.class) {
395 form = VarHandleSegmentAsShorts.selectForm(alignmentMask, constantOffset);
396 } else if (carrier == int.class) {
397 form = VarHandleSegmentAsInts.selectForm(alignmentMask, constantOffset);
398 } else if (carrier == float.class) {
399 form = VarHandleSegmentAsFloats.selectForm(alignmentMask, constantOffset);
400 } else if (carrier == long.class) {
401 form = VarHandleSegmentAsLongs.selectForm(alignmentMask, constantOffset);
402 } else if (carrier == double.class) {
403 form = VarHandleSegmentAsDoubles.selectForm(alignmentMask, constantOffset);
404 } else if (carrier == boolean.class) {
405 form = VarHandleSegmentAsBooleans.selectForm(alignmentMask, constantOffset);
406 } else {
407 throw new IllegalStateException("Cannot get here");
408 }
409
410 return maybeAdapt(new SegmentVarHandle(form, be, enclosing, offset, exact));
411 }
412
413 private static VarHandle maybeAdapt(VarHandle target) {
414 if (!VAR_HANDLE_IDENTITY_ADAPT) return target;
415 target = filterValue(target,
416 MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType()));
417 MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET);
418 for (int i = 0 ; i < mtype.parameterCount() ; i++) {
419 target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i)));
420 }
421 return target;
422 }
423
424 public static VarHandle filterValue(VarHandle target, MethodHandle pFilterToTarget, MethodHandle pFilterFromTarget) {
425 Objects.requireNonNull(target);
426 Objects.requireNonNull(pFilterToTarget);
427 Objects.requireNonNull(pFilterFromTarget);
428 //check that from/to filters do not throw checked exceptions
429 MethodHandle filterToTarget = adaptForCheckedExceptions(pFilterToTarget);
430 MethodHandle filterFromTarget = adaptForCheckedExceptions(pFilterFromTarget);
431
432 List<Class<?>> newCoordinates = new ArrayList<>();
433 List<Class<?>> additionalCoordinates = new ArrayList<>();
434 newCoordinates.addAll(target.coordinateTypes());
435
436 //check that from/to filters have right signatures
437 if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) {
438 throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type());
439 } else if (filterFromTarget.type().parameterCount() < 1) {
440 throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type());
441 } else if (filterToTarget.type().parameterCount() < 1) {
442 throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type());
443 } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() ||
444 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) {
445 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
446 } else if (target.varType() != filterFromTarget.type().lastParameterType()) {
447 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType());
448 } else if (target.varType() != filterToTarget.type().returnType()) {
449 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType());
450 } else if (filterFromTarget.type().parameterCount() > 1) {
451 for (int i = 0 ; i < filterFromTarget.type().parameterCount() - 1 ; i++) {
452 if (filterFromTarget.type().parameterType(i) != filterToTarget.type().parameterType(i)) {
453 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
454 } else {
455 newCoordinates.add(filterFromTarget.type().parameterType(i));
456 additionalCoordinates.add((filterFromTarget.type().parameterType(i)));
457 }
458 }
459 }
460
461 return new IndirectVarHandle(target, filterFromTarget.type().returnType(), newCoordinates.toArray(new Class<?>[0]),
462 (mode, modeHandle) -> {
463 int lastParameterPos = modeHandle.type().parameterCount() - 1;
464 return switch (mode.at) {
465 case GET -> MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
466 case SET -> MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
467 case GET_AND_UPDATE -> {
468 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
469 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
470 if (additionalCoordinates.size() > 0) {
471 res = joinDuplicateArgs(res, lastParameterPos,
472 lastParameterPos + additionalCoordinates.size() + 1,
473 additionalCoordinates.size());
474 }
475 yield res;
476 }
477 case COMPARE_AND_EXCHANGE -> {
478 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
479 adapter = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
480 if (additionalCoordinates.size() > 0) {
481 adapter = joinDuplicateArgs(adapter, lastParameterPos,
482 lastParameterPos + additionalCoordinates.size() + 1,
483 additionalCoordinates.size());
484 }
485 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
486 if (additionalCoordinates.size() > 0) {
487 res = joinDuplicateArgs(res, lastParameterPos - 1,
488 lastParameterPos + additionalCoordinates.size(),
489 additionalCoordinates.size());
490 }
491 yield res;
492 }
493 case COMPARE_AND_SET -> {
494 MethodHandle adapter = MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
495 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
496 if (additionalCoordinates.size() > 0) {
497 res = joinDuplicateArgs(res, lastParameterPos - 1,
498 lastParameterPos + additionalCoordinates.size(),
499 additionalCoordinates.size());
500 }
501 yield res;
502 }
503 };
504 });
505 }
506
507 private static MethodHandle joinDuplicateArgs(MethodHandle handle, int originalStart, int dropStart, int length) {
508 int[] perms = new int[handle.type().parameterCount()];
509 for (int i = 0 ; i < dropStart; i++) {
510 perms[i] = i;
511 }
512 for (int i = 0 ; i < length ; i++) {
513 perms[dropStart + i] = originalStart + i;
514 }
515 for (int i = dropStart + length ; i < perms.length ; i++) {
516 perms[i] = i - length;
517 }
518 return MethodHandles.permuteArguments(handle,
519 handle.type().dropParameterTypes(dropStart, dropStart + length),
520 perms);
521 }
522
523 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
524 Objects.requireNonNull(target);
525 Objects.requireNonNull(filters);
526
527 List<Class<?>> targetCoordinates = target.coordinateTypes();
528 if (pos < 0 || pos >= targetCoordinates.size()) {
529 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
530 } else if (pos + filters.length > targetCoordinates.size()) {
531 throw new IllegalArgumentException("Too many filters");
532 }
533
534 if (filters.length == 0) return target;
535
536 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
537 for (int i = 0 ; i < filters.length ; i++) {
538 MethodHandle filter = Objects.requireNonNull(filters[i]);
539 filter = adaptForCheckedExceptions(filter);
540 MethodType filterType = filter.type();
541 if (filterType.parameterCount() != 1) {
542 throw newIllegalArgumentException("Invalid filter type " + filterType);
543 } else if (newCoordinates.get(pos + i) != filterType.returnType()) {
544 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i));
545 }
546 newCoordinates.set(pos + i, filters[i].type().parameterType(0));
547 }
548
549 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
550 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters));
551 }
552
553 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
554 Objects.requireNonNull(target);
555 Objects.requireNonNull(values);
556
557 List<Class<?>> targetCoordinates = target.coordinateTypes();
558 if (pos < 0 || pos >= targetCoordinates.size()) {
559 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
560 } else if (pos + values.length > targetCoordinates.size()) {
561 throw new IllegalArgumentException("Too many values");
562 }
563
564 if (values.length == 0) return target;
565
566 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
567 for (int i = 0 ; i < values.length ; i++) {
568 Class<?> pt = newCoordinates.get(pos);
569 if (pt.isPrimitive()) {
570 Wrapper w = Wrapper.forPrimitiveType(pt);
571 w.convert(values[i], pt);
572 } else {
573 pt.cast(values[i]);
574 }
575 newCoordinates.remove(pos);
576 }
577
578 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
579 (mode, modeHandle) -> MethodHandles.insertArguments(modeHandle, 1 + pos, values));
580 }
581
582 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
583 Objects.requireNonNull(target);
584 Objects.requireNonNull(newCoordinates);
585 Objects.requireNonNull(reorder);
586
587 List<Class<?>> targetCoordinates = target.coordinateTypes();
588 MethodHandles.permuteArgumentChecks(reorder,
589 MethodType.methodType(void.class, newCoordinates),
590 MethodType.methodType(void.class, targetCoordinates));
591
592 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
593 (mode, modeHandle) ->
594 MethodHandles.permuteArguments(modeHandle,
595 methodTypeFor(mode.at, modeHandle.type(), targetCoordinates, newCoordinates),
596 reorderArrayFor(mode.at, newCoordinates, reorder)));
597 }
598
599 private static int numTrailingArgs(VarHandle.AccessType at) {
600 return switch (at) {
601 case GET -> 0;
602 case GET_AND_UPDATE, SET -> 1;
603 case COMPARE_AND_SET, COMPARE_AND_EXCHANGE -> 2;
604 };
605 }
606
607 private static int[] reorderArrayFor(VarHandle.AccessType at, List<Class<?>> newCoordinates, int[] reorder) {
608 int numTrailingArgs = numTrailingArgs(at);
609 int[] adjustedReorder = new int[reorder.length + 1 + numTrailingArgs];
610 adjustedReorder[0] = 0;
611 for (int i = 0 ; i < reorder.length ; i++) {
612 adjustedReorder[i + 1] = reorder[i] + 1;
613 }
614 for (int i = 0 ; i < numTrailingArgs ; i++) {
615 adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1;
616 }
617 return adjustedReorder;
618 }
619
620 private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) {
621 int numTrailingArgs = numTrailingArgs(at);
622 MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0));
623 adjustedType = adjustedType.appendParameterTypes(newCoordinates);
624 for (int i = 0 ; i < numTrailingArgs ; i++) {
625 adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i));
626 }
627 return adjustedType;
628 }
629
630 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle pFilter) {
631 Objects.requireNonNull(target);
632 Objects.requireNonNull(pFilter);
633 MethodHandle filter = adaptForCheckedExceptions(pFilter);
634
635 List<Class<?>> targetCoordinates = target.coordinateTypes();
636 if (pos < 0 || pos >= targetCoordinates.size()) {
637 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
638 } else if (filter.type().returnType() != void.class && filter.type().returnType() != targetCoordinates.get(pos)) {
639 throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos));
640 }
641
642 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
643 if (filter.type().returnType() != void.class) {
644 newCoordinates.remove(pos);
645 }
646 newCoordinates.addAll(pos, filter.type().parameterList());
647
648 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
649 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter));
650 }
651
652 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
653 Objects.requireNonNull(target);
654 Objects.requireNonNull(valueTypes);
655
656 List<Class<?>> targetCoordinates = target.coordinateTypes();
657 if (pos < 0 || pos > targetCoordinates.size()) {
658 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
659 }
660
661 if (valueTypes.length == 0) return target;
662
663 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
664 newCoordinates.addAll(pos, List.of(valueTypes));
665
666 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
667 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
668 }
669
670 private static MethodHandle adaptForCheckedExceptions(MethodHandle target) {
671 Class<?>[] exceptionTypes = exceptionTypes(target);
672 if (exceptionTypes != null) { // exceptions known
673 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
674 throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
675 }
676 return target; // no adaptation needed
677 } else {
678 MethodHandle handler = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_VarHandles_handleCheckedExceptions);
679 MethodHandle zero = MethodHandles.zero(target.type().returnType()); // dead branch
680 handler = MethodHandles.collectArguments(zero, 0, handler);
681 return MethodHandles.catchException(target, Throwable.class, handler);
682 }
683 }
684
685 static void handleCheckedExceptions(Throwable throwable) throws Throwable {
686 if (isCheckedException(throwable.getClass())) {
687 throw new IllegalStateException("Adapter handle threw checked exception", throwable);
688 }
689 throw throwable;
690 }
691
692 static Class<?>[] exceptionTypes(MethodHandle handle) {
693 if (handle instanceof DirectMethodHandle directHandle) {
694 byte refKind = directHandle.member.getReferenceKind();
695 MethodHandleInfo info = new InfoFromMemberName(
696 MethodHandles.Lookup.IMPL_LOOKUP,
697 directHandle.member,
698 refKind);
699 if (MethodHandleNatives.refKindIsMethod(refKind)) {
700 return info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
701 .getExceptionTypes();
702 } else if (MethodHandleNatives.refKindIsField(refKind)) {
703 return new Class<?>[0];
704 } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
705 return info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
706 .getExceptionTypes();
707 } else {
708 throw new AssertionError("Cannot get here");
709 }
710 } else if (handle instanceof DelegatingMethodHandle delegatingMh) {
711 return exceptionTypes(delegatingMh.getTarget());
712 } else if (handle instanceof NativeMethodHandle) {
713 return new Class<?>[0];
714 }
715
716 assert handle instanceof BoundMethodHandle : "Unexpected handle type: " + handle;
717 // unknown
718 return null;
719 }
720
721 private static boolean isCheckedException(Class<?> clazz) {
722 return Throwable.class.isAssignableFrom(clazz) &&
723 !RuntimeException.class.isAssignableFrom(clazz) &&
724 !Error.class.isAssignableFrom(clazz);
725 }
726 }