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