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