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 sun.invoke.util.Wrapper;
30
31 import java.lang.foreign.MemoryLayout;
32 import java.lang.reflect.Constructor;
33 import java.lang.reflect.Field;
34 import java.lang.reflect.Method;
35 import java.lang.reflect.Modifier;
36 import java.nio.ByteOrder;
37 import java.util.ArrayList;
38 import java.util.List;
39 import java.util.Objects;
40 import java.util.stream.Stream;
41
42 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
43 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_SEGMENT_FORCE_EXACT;
44 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT;
45 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
46
47 final class VarHandles {
48
49 static VarHandle makeFieldHandle(MemberName f, Class<?> refc, boolean isWriteAllowedOnFinalFields) {
50 if (!f.isStatic()) {
51 long foffset = MethodHandleNatives.objectFieldOffset(f);
52 Class<?> type = f.getFieldType();
53 if (!type.isPrimitive()) {
54 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
55 ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type)
56 : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type));
57 }
58 else if (type == boolean.class) {
59 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
60 ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset)
61 : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset));
62 }
63 else if (type == byte.class) {
64 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
65 ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset)
66 : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset));
67 }
68 else if (type == short.class) {
69 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
70 ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset)
71 : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset));
72 }
73 else if (type == char.class) {
74 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
75 ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset)
76 : new VarHandleChars.FieldInstanceReadWrite(refc, foffset));
77 }
78 else if (type == int.class) {
79 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
80 ? new VarHandleInts.FieldInstanceReadOnly(refc, foffset)
81 : new VarHandleInts.FieldInstanceReadWrite(refc, foffset));
82 }
83 else if (type == long.class) {
84 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
85 ? new VarHandleLongs.FieldInstanceReadOnly(refc, foffset)
86 : new VarHandleLongs.FieldInstanceReadWrite(refc, foffset));
87 }
88 else if (type == float.class) {
89 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
90 ? new VarHandleFloats.FieldInstanceReadOnly(refc, foffset)
91 : new VarHandleFloats.FieldInstanceReadWrite(refc, foffset));
92 }
93 else if (type == double.class) {
94 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
95 ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset)
96 : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset));
97 }
98 else {
99 throw new UnsupportedOperationException();
100 }
101 }
102 else {
103 Class<?> decl = f.getDeclaringClass();
104 var vh = makeStaticFieldVarHandle(decl, f, isWriteAllowedOnFinalFields);
105 return maybeAdapt((UNSAFE.shouldBeInitialized(decl) || CDS.needsClassInitBarrier(decl))
106 ? new LazyInitializingVarHandle(vh, decl)
107 : vh);
108 }
109 }
110
111 static VarHandle makeStaticFieldVarHandle(Class<?> decl, MemberName f, boolean isWriteAllowedOnFinalFields) {
112 Object base = MethodHandleNatives.staticFieldBase(f);
113 long foffset = MethodHandleNatives.staticFieldOffset(f);
114 Class<?> type = f.getFieldType();
115 if (!type.isPrimitive()) {
116 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
117 ? new VarHandleReferences.FieldStaticReadOnly(decl, base, foffset, type)
118 : new VarHandleReferences.FieldStaticReadWrite(decl, base, foffset, type));
119 }
120 else if (type == boolean.class) {
121 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
122 ? new VarHandleBooleans.FieldStaticReadOnly(decl, base, foffset)
123 : new VarHandleBooleans.FieldStaticReadWrite(decl, base, foffset));
124 }
125 else if (type == byte.class) {
126 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
127 ? new VarHandleBytes.FieldStaticReadOnly(decl, base, foffset)
128 : new VarHandleBytes.FieldStaticReadWrite(decl, base, foffset));
129 }
130 else if (type == short.class) {
131 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
132 ? new VarHandleShorts.FieldStaticReadOnly(decl, base, foffset)
133 : new VarHandleShorts.FieldStaticReadWrite(decl, base, foffset));
134 }
135 else if (type == char.class) {
136 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
137 ? new VarHandleChars.FieldStaticReadOnly(decl, base, foffset)
138 : new VarHandleChars.FieldStaticReadWrite(decl, base, foffset));
139 }
140 else if (type == int.class) {
141 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
142 ? new VarHandleInts.FieldStaticReadOnly(decl, base, foffset)
143 : new VarHandleInts.FieldStaticReadWrite(decl, base, foffset));
144 }
145 else if (type == long.class) {
146 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
147 ? new VarHandleLongs.FieldStaticReadOnly(decl, base, foffset)
148 : new VarHandleLongs.FieldStaticReadWrite(decl, base, foffset));
149 }
150 else if (type == float.class) {
151 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
152 ? new VarHandleFloats.FieldStaticReadOnly(decl, base, foffset)
153 : new VarHandleFloats.FieldStaticReadWrite(decl, base, foffset));
154 }
155 else if (type == double.class) {
156 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields
157 ? new VarHandleDoubles.FieldStaticReadOnly(decl, base, foffset)
158 : new VarHandleDoubles.FieldStaticReadWrite(decl, base, foffset));
159 }
160 else {
161 throw new UnsupportedOperationException();
162 }
163 }
164
165 // Required by instance field handles
166 static Field getFieldFromReceiverAndOffset(Class<?> receiverType,
167 long offset,
168 Class<?> fieldType) {
169 // The receiver may be a referenced class different from the declaring class
170 for (var declaringClass = receiverType; declaringClass != null; declaringClass = declaringClass.getSuperclass()) {
171 for (Field f : declaringClass.getDeclaredFields()) {
172 if (Modifier.isStatic(f.getModifiers())) continue;
173
174 if (offset == UNSAFE.objectFieldOffset(f)) {
175 assert f.getType() == fieldType;
176 return f;
177 }
178 }
179 }
180 throw new InternalError("Field not found at offset");
181 }
182
183 // Required by instance static field handles
184 static Field getStaticFieldFromBaseAndOffset(Class<?> declaringClass,
185 long offset,
186 Class<?> fieldType) {
187 for (Field f : declaringClass.getDeclaredFields()) {
188 if (!Modifier.isStatic(f.getModifiers())) continue;
189
190 if (offset == UNSAFE.staticFieldOffset(f)) {
191 assert f.getType() == fieldType;
192 return f;
193 }
194 }
195 throw new InternalError("Static field not found at offset");
196 }
197
198 static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
199 if (!arrayClass.isArray())
200 throw new IllegalArgumentException("not an array: " + arrayClass);
201
202 Class<?> componentType = arrayClass.getComponentType();
203
204 int aoffset = (int) UNSAFE.arrayBaseOffset(arrayClass);
205 int ascale = UNSAFE.arrayIndexScale(arrayClass);
206 int ashift = 31 - Integer.numberOfLeadingZeros(ascale);
207
208 if (!componentType.isPrimitive()) {
209 return maybeAdapt(new VarHandleReferences.Array(aoffset, ashift, arrayClass));
210 }
211 else if (componentType == boolean.class) {
212 return maybeAdapt(new VarHandleBooleans.Array(aoffset, ashift));
213 }
214 else if (componentType == byte.class) {
215 return maybeAdapt(new VarHandleBytes.Array(aoffset, ashift));
216 }
217 else if (componentType == short.class) {
218 return maybeAdapt(new VarHandleShorts.Array(aoffset, ashift));
219 }
220 else if (componentType == char.class) {
221 return maybeAdapt(new VarHandleChars.Array(aoffset, ashift));
222 }
223 else if (componentType == int.class) {
224 return maybeAdapt(new VarHandleInts.Array(aoffset, ashift));
225 }
226 else if (componentType == long.class) {
227 return maybeAdapt(new VarHandleLongs.Array(aoffset, ashift));
228 }
229 else if (componentType == float.class) {
230 return maybeAdapt(new VarHandleFloats.Array(aoffset, ashift));
231 }
232 else if (componentType == double.class) {
233 return maybeAdapt(new VarHandleDoubles.Array(aoffset, ashift));
234 }
235 else {
236 throw new UnsupportedOperationException();
237 }
238 }
239
240 static VarHandle byteArrayViewHandle(Class<?> viewArrayClass,
241 boolean be) {
242 if (!viewArrayClass.isArray())
243 throw new IllegalArgumentException("not an array: " + viewArrayClass);
244
245 Class<?> viewComponentType = viewArrayClass.getComponentType();
246
247 if (viewComponentType == long.class) {
248 return maybeAdapt(new VarHandleByteArrayAsLongs.ArrayHandle(be));
249 }
250 else if (viewComponentType == int.class) {
251 return maybeAdapt(new VarHandleByteArrayAsInts.ArrayHandle(be));
252 }
253 else if (viewComponentType == short.class) {
254 return maybeAdapt(new VarHandleByteArrayAsShorts.ArrayHandle(be));
255 }
256 else if (viewComponentType == char.class) {
257 return maybeAdapt(new VarHandleByteArrayAsChars.ArrayHandle(be));
258 }
259 else if (viewComponentType == double.class) {
260 return maybeAdapt(new VarHandleByteArrayAsDoubles.ArrayHandle(be));
261 }
262 else if (viewComponentType == float.class) {
263 return maybeAdapt(new VarHandleByteArrayAsFloats.ArrayHandle(be));
264 }
265
266 throw new UnsupportedOperationException();
267 }
268
269 static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass,
270 boolean be) {
271 if (!viewArrayClass.isArray())
272 throw new IllegalArgumentException("not an array: " + viewArrayClass);
273
274 Class<?> viewComponentType = viewArrayClass.getComponentType();
275
276 if (viewComponentType == long.class) {
277 return maybeAdapt(new VarHandleByteArrayAsLongs.ByteBufferHandle(be));
278 }
279 else if (viewComponentType == int.class) {
280 return maybeAdapt(new VarHandleByteArrayAsInts.ByteBufferHandle(be));
281 }
282 else if (viewComponentType == short.class) {
283 return maybeAdapt(new VarHandleByteArrayAsShorts.ByteBufferHandle(be));
284 }
285 else if (viewComponentType == char.class) {
286 return maybeAdapt(new VarHandleByteArrayAsChars.ByteBufferHandle(be));
287 }
288 else if (viewComponentType == double.class) {
289 return maybeAdapt(new VarHandleByteArrayAsDoubles.ByteBufferHandle(be));
290 }
291 else if (viewComponentType == float.class) {
292 return maybeAdapt(new VarHandleByteArrayAsFloats.ByteBufferHandle(be));
293 }
294
295 throw new UnsupportedOperationException();
296 }
297
298 /**
299 * Creates a memory segment view var handle accessing a {@code carrier} element. It has access coordinates
300 * {@code (MS, long)} if {@code constantOffset}, {@code (MS, long, (validated) long)} otherwise.
301 * <p>
302 * The resulting var handle will take a memory segment as first argument (the segment to be dereferenced),
303 * and a {@code long} as second argument (the offset into the segment). Both arguments are checked.
304 * <p>
305 * If {@code constantOffset == false}, the resulting var handle will take a third pre-validated additional
306 * offset instead of the given fixed {@code offset}, and caller must ensure that passed additional offset,
307 * either to the handle (such as computing through method handles) or as fixed {@code offset} here, is valid.
308 *
309 * @param carrier the Java carrier type of the element
310 * @param enclosing the enclosing layout to perform bound and alignment checks against
311 * @param alignmentMask alignment of this accessed element in the enclosing layout
312 * @param constantOffset if access path has a constant offset value, i.e. it has no strides
313 * @param offset the offset value, if the offset is constant
314 * @param byteOrder the byte order
315 * @return the created var handle
316 */
317 static VarHandle memorySegmentViewHandle(Class<?> carrier, MemoryLayout enclosing, long alignmentMask,
318 boolean constantOffset, long offset, ByteOrder byteOrder) {
319 if (!carrier.isPrimitive() || carrier == void.class) {
320 throw new IllegalArgumentException("Invalid carrier: " + carrier.getName());
321 }
322 boolean be = byteOrder == ByteOrder.BIG_ENDIAN;
323 boolean exact = VAR_HANDLE_SEGMENT_FORCE_EXACT;
324
325 // All carrier types must persist across MethodType erasure
326 VarForm form;
327 if (carrier == byte.class) {
328 form = VarHandleSegmentAsBytes.selectForm(alignmentMask, constantOffset);
329 } else if (carrier == char.class) {
330 form = VarHandleSegmentAsChars.selectForm(alignmentMask, constantOffset);
331 } else if (carrier == short.class) {
332 form = VarHandleSegmentAsShorts.selectForm(alignmentMask, constantOffset);
333 } else if (carrier == int.class) {
334 form = VarHandleSegmentAsInts.selectForm(alignmentMask, constantOffset);
335 } else if (carrier == float.class) {
336 form = VarHandleSegmentAsFloats.selectForm(alignmentMask, constantOffset);
337 } else if (carrier == long.class) {
338 form = VarHandleSegmentAsLongs.selectForm(alignmentMask, constantOffset);
339 } else if (carrier == double.class) {
340 form = VarHandleSegmentAsDoubles.selectForm(alignmentMask, constantOffset);
341 } else if (carrier == boolean.class) {
342 form = VarHandleSegmentAsBooleans.selectForm(alignmentMask, constantOffset);
343 } else {
344 throw new IllegalStateException("Cannot get here");
345 }
346
347 return maybeAdapt(new SegmentVarHandle(form, be, enclosing, offset, exact));
348 }
349
350 private static VarHandle maybeAdapt(VarHandle target) {
351 if (!VAR_HANDLE_IDENTITY_ADAPT) return target;
352 target = filterValue(target,
353 MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType()));
354 MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET);
355 for (int i = 0 ; i < mtype.parameterCount() ; i++) {
356 target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i)));
357 }
358 return target;
359 }
360
361 public static VarHandle filterValue(VarHandle target, MethodHandle pFilterToTarget, MethodHandle pFilterFromTarget) {
362 Objects.requireNonNull(target);
363 Objects.requireNonNull(pFilterToTarget);
364 Objects.requireNonNull(pFilterFromTarget);
365 //check that from/to filters do not throw checked exceptions
366 MethodHandle filterToTarget = adaptForCheckedExceptions(pFilterToTarget);
367 MethodHandle filterFromTarget = adaptForCheckedExceptions(pFilterFromTarget);
368
369 List<Class<?>> newCoordinates = new ArrayList<>();
370 List<Class<?>> additionalCoordinates = new ArrayList<>();
371 newCoordinates.addAll(target.coordinateTypes());
372
373 //check that from/to filters have right signatures
374 if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) {
375 throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type());
376 } else if (filterFromTarget.type().parameterCount() < 1) {
377 throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type());
378 } else if (filterToTarget.type().parameterCount() < 1) {
379 throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type());
380 } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() ||
381 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) {
382 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
383 } else if (target.varType() != filterFromTarget.type().lastParameterType()) {
384 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType());
385 } else if (target.varType() != filterToTarget.type().returnType()) {
386 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType());
387 } else if (filterFromTarget.type().parameterCount() > 1) {
388 for (int i = 0 ; i < filterFromTarget.type().parameterCount() - 1 ; i++) {
389 if (filterFromTarget.type().parameterType(i) != filterToTarget.type().parameterType(i)) {
390 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type());
391 } else {
392 newCoordinates.add(filterFromTarget.type().parameterType(i));
393 additionalCoordinates.add((filterFromTarget.type().parameterType(i)));
394 }
395 }
396 }
397
398 return new IndirectVarHandle(target, filterFromTarget.type().returnType(), newCoordinates.toArray(new Class<?>[0]),
399 (mode, modeHandle) -> {
400 int lastParameterPos = modeHandle.type().parameterCount() - 1;
401 return switch (mode.at) {
402 case GET -> MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
403 case SET -> MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
404 case GET_AND_UPDATE -> {
405 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
406 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
407 if (additionalCoordinates.size() > 0) {
408 res = joinDuplicateArgs(res, lastParameterPos,
409 lastParameterPos + additionalCoordinates.size() + 1,
410 additionalCoordinates.size());
411 }
412 yield res;
413 }
414 case COMPARE_AND_EXCHANGE -> {
415 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget);
416 adapter = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget);
417 if (additionalCoordinates.size() > 0) {
418 adapter = joinDuplicateArgs(adapter, lastParameterPos,
419 lastParameterPos + additionalCoordinates.size() + 1,
420 additionalCoordinates.size());
421 }
422 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
423 if (additionalCoordinates.size() > 0) {
424 res = joinDuplicateArgs(res, lastParameterPos - 1,
425 lastParameterPos + additionalCoordinates.size(),
426 additionalCoordinates.size());
427 }
428 yield res;
429 }
430 case COMPARE_AND_SET -> {
431 MethodHandle adapter = MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget);
432 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget);
433 if (additionalCoordinates.size() > 0) {
434 res = joinDuplicateArgs(res, lastParameterPos - 1,
435 lastParameterPos + additionalCoordinates.size(),
436 additionalCoordinates.size());
437 }
438 yield res;
439 }
440 };
441 });
442 }
443
444 private static MethodHandle joinDuplicateArgs(MethodHandle handle, int originalStart, int dropStart, int length) {
445 int[] perms = new int[handle.type().parameterCount()];
446 for (int i = 0 ; i < dropStart; i++) {
447 perms[i] = i;
448 }
449 for (int i = 0 ; i < length ; i++) {
450 perms[dropStart + i] = originalStart + i;
451 }
452 for (int i = dropStart + length ; i < perms.length ; i++) {
453 perms[i] = i - length;
454 }
455 return MethodHandles.permuteArguments(handle,
456 handle.type().dropParameterTypes(dropStart, dropStart + length),
457 perms);
458 }
459
460 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) {
461 Objects.requireNonNull(target);
462 Objects.requireNonNull(filters);
463
464 List<Class<?>> targetCoordinates = target.coordinateTypes();
465 if (pos < 0 || pos >= targetCoordinates.size()) {
466 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
467 } else if (pos + filters.length > targetCoordinates.size()) {
468 throw new IllegalArgumentException("Too many filters");
469 }
470
471 if (filters.length == 0) return target;
472
473 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
474 for (int i = 0 ; i < filters.length ; i++) {
475 MethodHandle filter = Objects.requireNonNull(filters[i]);
476 filter = adaptForCheckedExceptions(filter);
477 MethodType filterType = filter.type();
478 if (filterType.parameterCount() != 1) {
479 throw newIllegalArgumentException("Invalid filter type " + filterType);
480 } else if (newCoordinates.get(pos + i) != filterType.returnType()) {
481 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i));
482 }
483 newCoordinates.set(pos + i, filters[i].type().parameterType(0));
484 }
485
486 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
487 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters));
488 }
489
490 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) {
491 Objects.requireNonNull(target);
492 Objects.requireNonNull(values);
493
494 List<Class<?>> targetCoordinates = target.coordinateTypes();
495 if (pos < 0 || pos >= targetCoordinates.size()) {
496 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
497 } else if (pos + values.length > targetCoordinates.size()) {
498 throw new IllegalArgumentException("Too many values");
499 }
500
501 if (values.length == 0) return target;
502
503 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
504 for (int i = 0 ; i < values.length ; i++) {
505 Class<?> pt = newCoordinates.get(pos);
506 if (pt.isPrimitive()) {
507 Wrapper w = Wrapper.forPrimitiveType(pt);
508 w.convert(values[i], pt);
509 } else {
510 pt.cast(values[i]);
511 }
512 newCoordinates.remove(pos);
513 }
514
515 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
516 (mode, modeHandle) -> MethodHandles.insertArguments(modeHandle, 1 + pos, values));
517 }
518
519 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) {
520 Objects.requireNonNull(target);
521 Objects.requireNonNull(newCoordinates);
522 Objects.requireNonNull(reorder);
523
524 List<Class<?>> targetCoordinates = target.coordinateTypes();
525 MethodHandles.permuteArgumentChecks(reorder,
526 MethodType.methodType(void.class, newCoordinates),
527 MethodType.methodType(void.class, targetCoordinates));
528
529 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
530 (mode, modeHandle) ->
531 MethodHandles.permuteArguments(modeHandle,
532 methodTypeFor(mode.at, modeHandle.type(), targetCoordinates, newCoordinates),
533 reorderArrayFor(mode.at, newCoordinates, reorder)));
534 }
535
536 private static int numTrailingArgs(VarHandle.AccessType at) {
537 return switch (at) {
538 case GET -> 0;
539 case GET_AND_UPDATE, SET -> 1;
540 case COMPARE_AND_SET, COMPARE_AND_EXCHANGE -> 2;
541 };
542 }
543
544 private static int[] reorderArrayFor(VarHandle.AccessType at, List<Class<?>> newCoordinates, int[] reorder) {
545 int numTrailingArgs = numTrailingArgs(at);
546 int[] adjustedReorder = new int[reorder.length + 1 + numTrailingArgs];
547 adjustedReorder[0] = 0;
548 for (int i = 0 ; i < reorder.length ; i++) {
549 adjustedReorder[i + 1] = reorder[i] + 1;
550 }
551 for (int i = 0 ; i < numTrailingArgs ; i++) {
552 adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1;
553 }
554 return adjustedReorder;
555 }
556
557 private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) {
558 int numTrailingArgs = numTrailingArgs(at);
559 MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0));
560 adjustedType = adjustedType.appendParameterTypes(newCoordinates);
561 for (int i = 0 ; i < numTrailingArgs ; i++) {
562 adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i));
563 }
564 return adjustedType;
565 }
566
567 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle pFilter) {
568 Objects.requireNonNull(target);
569 Objects.requireNonNull(pFilter);
570 MethodHandle filter = adaptForCheckedExceptions(pFilter);
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 (filter.type().returnType() != void.class && filter.type().returnType() != targetCoordinates.get(pos)) {
576 throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos));
577 }
578
579 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
580 if (filter.type().returnType() != void.class) {
581 newCoordinates.remove(pos);
582 }
583 newCoordinates.addAll(pos, filter.type().parameterList());
584
585 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
586 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter));
587 }
588
589 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) {
590 Objects.requireNonNull(target);
591 Objects.requireNonNull(valueTypes);
592
593 List<Class<?>> targetCoordinates = target.coordinateTypes();
594 if (pos < 0 || pos > targetCoordinates.size()) {
595 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates);
596 }
597
598 if (valueTypes.length == 0) return target;
599
600 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates);
601 newCoordinates.addAll(pos, List.of(valueTypes));
602
603 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]),
604 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes));
605 }
606
607 private static MethodHandle adaptForCheckedExceptions(MethodHandle target) {
608 Class<?>[] exceptionTypes = exceptionTypes(target);
609 if (exceptionTypes != null) { // exceptions known
610 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) {
611 throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions");
612 }
613 return target; // no adaptation needed
614 } else {
615 MethodHandle handler = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_VarHandles_handleCheckedExceptions);
616 MethodHandle zero = MethodHandles.zero(target.type().returnType()); // dead branch
617 handler = MethodHandles.collectArguments(zero, 0, handler);
618 return MethodHandles.catchException(target, Throwable.class, handler);
619 }
620 }
621
622 static void handleCheckedExceptions(Throwable throwable) throws Throwable {
623 if (isCheckedException(throwable.getClass())) {
624 throw new IllegalStateException("Adapter handle threw checked exception", throwable);
625 }
626 throw throwable;
627 }
628
629 static Class<?>[] exceptionTypes(MethodHandle handle) {
630 if (handle instanceof DirectMethodHandle directHandle) {
631 byte refKind = directHandle.member.getReferenceKind();
632 MethodHandleInfo info = new InfoFromMemberName(
633 MethodHandles.Lookup.IMPL_LOOKUP,
634 directHandle.member,
635 refKind);
636 if (MethodHandleNatives.refKindIsMethod(refKind)) {
637 return info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP)
638 .getExceptionTypes();
639 } else if (MethodHandleNatives.refKindIsField(refKind)) {
640 return new Class<?>[0];
641 } else if (MethodHandleNatives.refKindIsConstructor(refKind)) {
642 return info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP)
643 .getExceptionTypes();
644 } else {
645 throw new AssertionError("Cannot get here");
646 }
647 } else if (handle instanceof DelegatingMethodHandle delegatingMh) {
648 return exceptionTypes(delegatingMh.getTarget());
649 } else if (handle instanceof NativeMethodHandle) {
650 return new Class<?>[0];
651 }
652
653 assert handle instanceof BoundMethodHandle : "Unexpected handle type: " + handle;
654 // unknown
655 return null;
656 }
657
658 private static boolean isCheckedException(Class<?> clazz) {
659 return Throwable.class.isAssignableFrom(clazz) &&
660 !RuntimeException.class.isAssignableFrom(clazz) &&
661 !Error.class.isAssignableFrom(clazz);
662 }
663 }