1 /* 2 * Copyright (c) 2014, 2023, 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.foreign.Utils; 29 import sun.invoke.util.Wrapper; 30 31 import java.lang.reflect.Constructor; 32 import java.lang.reflect.Field; 33 import java.lang.reflect.Method; 34 import java.lang.reflect.Modifier; 35 import java.nio.ByteOrder; 36 import java.util.ArrayList; 37 import java.util.List; 38 import java.util.Objects; 39 import java.util.concurrent.ConcurrentHashMap; 40 import java.util.concurrent.ConcurrentMap; 41 import java.util.stream.Stream; 42 43 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 44 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_SEGMENT_FORCE_EXACT; 45 import static java.lang.invoke.MethodHandleStatics.VAR_HANDLE_IDENTITY_ADAPT; 46 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 47 48 final class VarHandles { 49 50 static ClassValue<ConcurrentMap<Integer, MethodHandle>> ADDRESS_FACTORIES = new ClassValue<>() { 51 @Override 52 protected ConcurrentMap<Integer, MethodHandle> computeValue(Class<?> type) { 53 return new ConcurrentHashMap<>(); 54 } 55 }; 56 57 static VarHandle makeFieldHandle(MemberName f, Class<?> refc, boolean isWriteAllowedOnFinalFields) { 58 if (!f.isStatic()) { 59 long foffset = MethodHandleNatives.objectFieldOffset(f); 60 Class<?> type = f.getFieldType(); 61 if (!type.isPrimitive()) { 62 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 63 ? new VarHandleReferences.FieldInstanceReadOnly(refc, foffset, type) 64 : new VarHandleReferences.FieldInstanceReadWrite(refc, foffset, type)); 65 } 66 else if (type == boolean.class) { 67 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 68 ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset) 69 : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset)); 70 } 71 else if (type == byte.class) { 72 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 73 ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset) 74 : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset)); 75 } 76 else if (type == short.class) { 77 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 78 ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset) 79 : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset)); 80 } 81 else if (type == char.class) { 82 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 83 ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset) 84 : new VarHandleChars.FieldInstanceReadWrite(refc, foffset)); 85 } 86 else if (type == int.class) { 87 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 88 ? new VarHandleInts.FieldInstanceReadOnly(refc, foffset) 89 : new VarHandleInts.FieldInstanceReadWrite(refc, foffset)); 90 } 91 else if (type == long.class) { 92 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 93 ? new VarHandleLongs.FieldInstanceReadOnly(refc, foffset) 94 : new VarHandleLongs.FieldInstanceReadWrite(refc, foffset)); 95 } 96 else if (type == float.class) { 97 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 98 ? new VarHandleFloats.FieldInstanceReadOnly(refc, foffset) 99 : new VarHandleFloats.FieldInstanceReadWrite(refc, foffset)); 100 } 101 else if (type == double.class) { 102 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 103 ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset) 104 : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset)); 105 } 106 else { 107 throw new UnsupportedOperationException(); 108 } 109 } 110 else { 111 Class<?> decl = f.getDeclaringClass(); 112 var vh = makeStaticFieldVarHandle(decl, f, isWriteAllowedOnFinalFields); 113 return maybeAdapt(UNSAFE.shouldBeInitialized(decl) 114 ? new LazyInitializingVarHandle(vh, decl) 115 : vh); 116 } 117 } 118 119 static VarHandle makeStaticFieldVarHandle(Class<?> decl, MemberName f, boolean isWriteAllowedOnFinalFields) { 120 Object base = MethodHandleNatives.staticFieldBase(f); 121 long foffset = MethodHandleNatives.staticFieldOffset(f); 122 Class<?> type = f.getFieldType(); 123 if (!type.isPrimitive()) { 124 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 125 ? new VarHandleReferences.FieldStaticReadOnly(decl, base, foffset, type) 126 : new VarHandleReferences.FieldStaticReadWrite(decl, base, foffset, type)); 127 } 128 else if (type == boolean.class) { 129 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 130 ? new VarHandleBooleans.FieldStaticReadOnly(decl, base, foffset) 131 : new VarHandleBooleans.FieldStaticReadWrite(decl, base, foffset)); 132 } 133 else if (type == byte.class) { 134 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 135 ? new VarHandleBytes.FieldStaticReadOnly(decl, base, foffset) 136 : new VarHandleBytes.FieldStaticReadWrite(decl, base, foffset)); 137 } 138 else if (type == short.class) { 139 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 140 ? new VarHandleShorts.FieldStaticReadOnly(decl, base, foffset) 141 : new VarHandleShorts.FieldStaticReadWrite(decl, base, foffset)); 142 } 143 else if (type == char.class) { 144 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 145 ? new VarHandleChars.FieldStaticReadOnly(decl, base, foffset) 146 : new VarHandleChars.FieldStaticReadWrite(decl, base, foffset)); 147 } 148 else if (type == int.class) { 149 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 150 ? new VarHandleInts.FieldStaticReadOnly(decl, base, foffset) 151 : new VarHandleInts.FieldStaticReadWrite(decl, base, foffset)); 152 } 153 else if (type == long.class) { 154 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 155 ? new VarHandleLongs.FieldStaticReadOnly(decl, base, foffset) 156 : new VarHandleLongs.FieldStaticReadWrite(decl, base, foffset)); 157 } 158 else if (type == float.class) { 159 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 160 ? new VarHandleFloats.FieldStaticReadOnly(decl, base, foffset) 161 : new VarHandleFloats.FieldStaticReadWrite(decl, base, foffset)); 162 } 163 else if (type == double.class) { 164 return maybeAdapt(f.isFinal() && !isWriteAllowedOnFinalFields 165 ? new VarHandleDoubles.FieldStaticReadOnly(decl, base, foffset) 166 : new VarHandleDoubles.FieldStaticReadWrite(decl, base, foffset)); 167 } 168 else { 169 throw new UnsupportedOperationException(); 170 } 171 } 172 173 // Required by instance field handles 174 static Field getFieldFromReceiverAndOffset(Class<?> receiverType, 175 long offset, 176 Class<?> fieldType) { 177 for (Field f : receiverType.getDeclaredFields()) { 178 if (Modifier.isStatic(f.getModifiers())) continue; 179 180 if (offset == UNSAFE.objectFieldOffset(f)) { 181 assert f.getType() == fieldType; 182 return f; 183 } 184 } 185 throw new InternalError("Field not found at offset"); 186 } 187 188 // Required by instance static field handles 189 static Field getStaticFieldFromBaseAndOffset(Class<?> declaringClass, 190 long offset, 191 Class<?> fieldType) { 192 for (Field f : declaringClass.getDeclaredFields()) { 193 if (!Modifier.isStatic(f.getModifiers())) continue; 194 195 if (offset == UNSAFE.staticFieldOffset(f)) { 196 assert f.getType() == fieldType; 197 return f; 198 } 199 } 200 throw new InternalError("Static field not found at offset"); 201 } 202 203 static VarHandle makeArrayElementHandle(Class<?> arrayClass) { 204 if (!arrayClass.isArray()) 205 throw new IllegalArgumentException("not an array: " + arrayClass); 206 207 Class<?> componentType = arrayClass.getComponentType(); 208 209 int aoffset = UNSAFE.arrayBaseOffset(arrayClass); 210 int ascale = UNSAFE.arrayIndexScale(arrayClass); 211 int ashift = 31 - Integer.numberOfLeadingZeros(ascale); 212 213 if (!componentType.isPrimitive()) { 214 return maybeAdapt(new VarHandleReferences.Array(aoffset, ashift, arrayClass)); 215 } 216 else if (componentType == boolean.class) { 217 return maybeAdapt(new VarHandleBooleans.Array(aoffset, ashift)); 218 } 219 else if (componentType == byte.class) { 220 return maybeAdapt(new VarHandleBytes.Array(aoffset, ashift)); 221 } 222 else if (componentType == short.class) { 223 return maybeAdapt(new VarHandleShorts.Array(aoffset, ashift)); 224 } 225 else if (componentType == char.class) { 226 return maybeAdapt(new VarHandleChars.Array(aoffset, ashift)); 227 } 228 else if (componentType == int.class) { 229 return maybeAdapt(new VarHandleInts.Array(aoffset, ashift)); 230 } 231 else if (componentType == long.class) { 232 return maybeAdapt(new VarHandleLongs.Array(aoffset, ashift)); 233 } 234 else if (componentType == float.class) { 235 return maybeAdapt(new VarHandleFloats.Array(aoffset, ashift)); 236 } 237 else if (componentType == double.class) { 238 return maybeAdapt(new VarHandleDoubles.Array(aoffset, ashift)); 239 } 240 else { 241 throw new UnsupportedOperationException(); 242 } 243 } 244 245 static VarHandle byteArrayViewHandle(Class<?> viewArrayClass, 246 boolean be) { 247 if (!viewArrayClass.isArray()) 248 throw new IllegalArgumentException("not an array: " + viewArrayClass); 249 250 Class<?> viewComponentType = viewArrayClass.getComponentType(); 251 252 if (viewComponentType == long.class) { 253 return maybeAdapt(new VarHandleByteArrayAsLongs.ArrayHandle(be)); 254 } 255 else if (viewComponentType == int.class) { 256 return maybeAdapt(new VarHandleByteArrayAsInts.ArrayHandle(be)); 257 } 258 else if (viewComponentType == short.class) { 259 return maybeAdapt(new VarHandleByteArrayAsShorts.ArrayHandle(be)); 260 } 261 else if (viewComponentType == char.class) { 262 return maybeAdapt(new VarHandleByteArrayAsChars.ArrayHandle(be)); 263 } 264 else if (viewComponentType == double.class) { 265 return maybeAdapt(new VarHandleByteArrayAsDoubles.ArrayHandle(be)); 266 } 267 else if (viewComponentType == float.class) { 268 return maybeAdapt(new VarHandleByteArrayAsFloats.ArrayHandle(be)); 269 } 270 271 throw new UnsupportedOperationException(); 272 } 273 274 static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass, 275 boolean be) { 276 if (!viewArrayClass.isArray()) 277 throw new IllegalArgumentException("not an array: " + viewArrayClass); 278 279 Class<?> viewComponentType = viewArrayClass.getComponentType(); 280 281 if (viewComponentType == long.class) { 282 return maybeAdapt(new VarHandleByteArrayAsLongs.ByteBufferHandle(be)); 283 } 284 else if (viewComponentType == int.class) { 285 return maybeAdapt(new VarHandleByteArrayAsInts.ByteBufferHandle(be)); 286 } 287 else if (viewComponentType == short.class) { 288 return maybeAdapt(new VarHandleByteArrayAsShorts.ByteBufferHandle(be)); 289 } 290 else if (viewComponentType == char.class) { 291 return maybeAdapt(new VarHandleByteArrayAsChars.ByteBufferHandle(be)); 292 } 293 else if (viewComponentType == double.class) { 294 return maybeAdapt(new VarHandleByteArrayAsDoubles.ByteBufferHandle(be)); 295 } 296 else if (viewComponentType == float.class) { 297 return maybeAdapt(new VarHandleByteArrayAsFloats.ByteBufferHandle(be)); 298 } 299 300 throw new UnsupportedOperationException(); 301 } 302 303 /** 304 * Creates a memory segment view var handle. 305 * 306 * The resulting var handle will take a memory segment as first argument (the segment to be dereferenced), 307 * and a {@code long} as second argument (the offset into the segment). 308 * 309 * @param carrier the Java carrier type. 310 * @param alignmentMask alignment requirement to be checked upon access. In bytes. Expressed as a mask. 311 * @param byteOrder the byte order. 312 * @return the created VarHandle. 313 */ 314 static VarHandle memorySegmentViewHandle(Class<?> carrier, long alignmentMask, 315 ByteOrder byteOrder) { 316 if (!carrier.isPrimitive() || carrier == void.class || carrier == boolean.class) { 317 throw new IllegalArgumentException("Invalid carrier: " + carrier.getName()); 318 } 319 long size = Utils.byteWidthOfPrimitive(carrier); 320 boolean be = byteOrder == ByteOrder.BIG_ENDIAN; 321 boolean exact = VAR_HANDLE_SEGMENT_FORCE_EXACT; 322 323 if (carrier == byte.class) { 324 return maybeAdapt(new VarHandleSegmentAsBytes(be, size, alignmentMask, exact)); 325 } else if (carrier == char.class) { 326 return maybeAdapt(new VarHandleSegmentAsChars(be, size, alignmentMask, exact)); 327 } else if (carrier == short.class) { 328 return maybeAdapt(new VarHandleSegmentAsShorts(be, size, alignmentMask, exact)); 329 } else if (carrier == int.class) { 330 return maybeAdapt(new VarHandleSegmentAsInts(be, size, alignmentMask, exact)); 331 } else if (carrier == float.class) { 332 return maybeAdapt(new VarHandleSegmentAsFloats(be, size, alignmentMask, exact)); 333 } else if (carrier == long.class) { 334 return maybeAdapt(new VarHandleSegmentAsLongs(be, size, alignmentMask, exact)); 335 } else if (carrier == double.class) { 336 return maybeAdapt(new VarHandleSegmentAsDoubles(be, size, alignmentMask, exact)); 337 } else { 338 throw new IllegalStateException("Cannot get here"); 339 } 340 } 341 342 private static VarHandle maybeAdapt(VarHandle target) { 343 if (!VAR_HANDLE_IDENTITY_ADAPT) return target; 344 target = filterValue(target, 345 MethodHandles.identity(target.varType()), MethodHandles.identity(target.varType())); 346 MethodType mtype = target.accessModeType(VarHandle.AccessMode.GET); 347 for (int i = 0 ; i < mtype.parameterCount() ; i++) { 348 target = filterCoordinates(target, i, MethodHandles.identity(mtype.parameterType(i))); 349 } 350 return target; 351 } 352 353 public static VarHandle filterValue(VarHandle target, MethodHandle pFilterToTarget, MethodHandle pFilterFromTarget) { 354 Objects.requireNonNull(target); 355 Objects.requireNonNull(pFilterToTarget); 356 Objects.requireNonNull(pFilterFromTarget); 357 //check that from/to filters do not throw checked exceptions 358 MethodHandle filterToTarget = adaptForCheckedExceptions(pFilterToTarget); 359 MethodHandle filterFromTarget = adaptForCheckedExceptions(pFilterFromTarget); 360 361 List<Class<?>> newCoordinates = new ArrayList<>(); 362 List<Class<?>> additionalCoordinates = new ArrayList<>(); 363 newCoordinates.addAll(target.coordinateTypes()); 364 365 //check that from/to filters have right signatures 366 if (filterFromTarget.type().parameterCount() != filterToTarget.type().parameterCount()) { 367 throw newIllegalArgumentException("filterFromTarget and filterToTarget have different arity", filterFromTarget.type(), filterToTarget.type()); 368 } else if (filterFromTarget.type().parameterCount() < 1) { 369 throw newIllegalArgumentException("filterFromTarget filter type has wrong arity", filterFromTarget.type()); 370 } else if (filterToTarget.type().parameterCount() < 1) { 371 throw newIllegalArgumentException("filterToTarget filter type has wrong arity", filterFromTarget.type()); 372 } else if (filterFromTarget.type().lastParameterType() != filterToTarget.type().returnType() || 373 filterToTarget.type().lastParameterType() != filterFromTarget.type().returnType()) { 374 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type()); 375 } else if (target.varType() != filterFromTarget.type().lastParameterType()) { 376 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterFromTarget.type(), target.varType()); 377 } else if (target.varType() != filterToTarget.type().returnType()) { 378 throw newIllegalArgumentException("filterFromTarget filter type does not match target var handle type", filterToTarget.type(), target.varType()); 379 } else if (filterFromTarget.type().parameterCount() > 1) { 380 for (int i = 0 ; i < filterFromTarget.type().parameterCount() - 1 ; i++) { 381 if (filterFromTarget.type().parameterType(i) != filterToTarget.type().parameterType(i)) { 382 throw newIllegalArgumentException("filterFromTarget and filterToTarget filter types do not match", filterFromTarget.type(), filterToTarget.type()); 383 } else { 384 newCoordinates.add(filterFromTarget.type().parameterType(i)); 385 additionalCoordinates.add((filterFromTarget.type().parameterType(i))); 386 } 387 } 388 } 389 390 return new IndirectVarHandle(target, filterFromTarget.type().returnType(), newCoordinates.toArray(new Class<?>[0]), 391 (mode, modeHandle) -> { 392 int lastParameterPos = modeHandle.type().parameterCount() - 1; 393 return switch (mode.at) { 394 case GET -> MethodHandles.collectReturnValue(modeHandle, filterFromTarget); 395 case SET -> MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget); 396 case GET_AND_UPDATE -> { 397 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget); 398 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget); 399 if (additionalCoordinates.size() > 0) { 400 res = joinDuplicateArgs(res, lastParameterPos, 401 lastParameterPos + additionalCoordinates.size() + 1, 402 additionalCoordinates.size()); 403 } 404 yield res; 405 } 406 case COMPARE_AND_EXCHANGE -> { 407 MethodHandle adapter = MethodHandles.collectReturnValue(modeHandle, filterFromTarget); 408 adapter = MethodHandles.collectArguments(adapter, lastParameterPos, filterToTarget); 409 if (additionalCoordinates.size() > 0) { 410 adapter = joinDuplicateArgs(adapter, lastParameterPos, 411 lastParameterPos + additionalCoordinates.size() + 1, 412 additionalCoordinates.size()); 413 } 414 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget); 415 if (additionalCoordinates.size() > 0) { 416 res = joinDuplicateArgs(res, lastParameterPos - 1, 417 lastParameterPos + additionalCoordinates.size(), 418 additionalCoordinates.size()); 419 } 420 yield res; 421 } 422 case COMPARE_AND_SET -> { 423 MethodHandle adapter = MethodHandles.collectArguments(modeHandle, lastParameterPos, filterToTarget); 424 MethodHandle res = MethodHandles.collectArguments(adapter, lastParameterPos - 1, filterToTarget); 425 if (additionalCoordinates.size() > 0) { 426 res = joinDuplicateArgs(res, lastParameterPos - 1, 427 lastParameterPos + additionalCoordinates.size(), 428 additionalCoordinates.size()); 429 } 430 yield res; 431 } 432 }; 433 }); 434 } 435 436 private static MethodHandle joinDuplicateArgs(MethodHandle handle, int originalStart, int dropStart, int length) { 437 int[] perms = new int[handle.type().parameterCount()]; 438 for (int i = 0 ; i < dropStart; i++) { 439 perms[i] = i; 440 } 441 for (int i = 0 ; i < length ; i++) { 442 perms[dropStart + i] = originalStart + i; 443 } 444 for (int i = dropStart + length ; i < perms.length ; i++) { 445 perms[i] = i - length; 446 } 447 return MethodHandles.permuteArguments(handle, 448 handle.type().dropParameterTypes(dropStart, dropStart + length), 449 perms); 450 } 451 452 public static VarHandle filterCoordinates(VarHandle target, int pos, MethodHandle... filters) { 453 Objects.requireNonNull(target); 454 Objects.requireNonNull(filters); 455 456 List<Class<?>> targetCoordinates = target.coordinateTypes(); 457 if (pos < 0 || pos >= targetCoordinates.size()) { 458 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates); 459 } else if (pos + filters.length > targetCoordinates.size()) { 460 throw new IllegalArgumentException("Too many filters"); 461 } 462 463 if (filters.length == 0) return target; 464 465 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates); 466 for (int i = 0 ; i < filters.length ; i++) { 467 MethodHandle filter = Objects.requireNonNull(filters[i]); 468 filter = adaptForCheckedExceptions(filter); 469 MethodType filterType = filter.type(); 470 if (filterType.parameterCount() != 1) { 471 throw newIllegalArgumentException("Invalid filter type " + filterType); 472 } else if (newCoordinates.get(pos + i) != filterType.returnType()) { 473 throw newIllegalArgumentException("Invalid filter type " + filterType + " for coordinate type " + newCoordinates.get(i)); 474 } 475 newCoordinates.set(pos + i, filters[i].type().parameterType(0)); 476 } 477 478 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]), 479 (mode, modeHandle) -> MethodHandles.filterArguments(modeHandle, 1 + pos, filters)); 480 } 481 482 public static VarHandle insertCoordinates(VarHandle target, int pos, Object... values) { 483 Objects.requireNonNull(target); 484 Objects.requireNonNull(values); 485 486 List<Class<?>> targetCoordinates = target.coordinateTypes(); 487 if (pos < 0 || pos >= targetCoordinates.size()) { 488 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates); 489 } else if (pos + values.length > targetCoordinates.size()) { 490 throw new IllegalArgumentException("Too many values"); 491 } 492 493 if (values.length == 0) return target; 494 495 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates); 496 for (int i = 0 ; i < values.length ; i++) { 497 Class<?> pt = newCoordinates.get(pos); 498 if (pt.isPrimitive()) { 499 Wrapper w = Wrapper.forPrimitiveType(pt); 500 w.convert(values[i], pt); 501 } else { 502 pt.cast(values[i]); 503 } 504 newCoordinates.remove(pos); 505 } 506 507 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]), 508 (mode, modeHandle) -> MethodHandles.insertArguments(modeHandle, 1 + pos, values)); 509 } 510 511 public static VarHandle permuteCoordinates(VarHandle target, List<Class<?>> newCoordinates, int... reorder) { 512 Objects.requireNonNull(target); 513 Objects.requireNonNull(newCoordinates); 514 Objects.requireNonNull(reorder); 515 516 List<Class<?>> targetCoordinates = target.coordinateTypes(); 517 MethodHandles.permuteArgumentChecks(reorder, 518 MethodType.methodType(void.class, newCoordinates), 519 MethodType.methodType(void.class, targetCoordinates)); 520 521 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]), 522 (mode, modeHandle) -> 523 MethodHandles.permuteArguments(modeHandle, 524 methodTypeFor(mode.at, modeHandle.type(), targetCoordinates, newCoordinates), 525 reorderArrayFor(mode.at, newCoordinates, reorder))); 526 } 527 528 private static int numTrailingArgs(VarHandle.AccessType at) { 529 return switch (at) { 530 case GET -> 0; 531 case GET_AND_UPDATE, SET -> 1; 532 case COMPARE_AND_SET, COMPARE_AND_EXCHANGE -> 2; 533 }; 534 } 535 536 private static int[] reorderArrayFor(VarHandle.AccessType at, List<Class<?>> newCoordinates, int[] reorder) { 537 int numTrailingArgs = numTrailingArgs(at); 538 int[] adjustedReorder = new int[reorder.length + 1 + numTrailingArgs]; 539 adjustedReorder[0] = 0; 540 for (int i = 0 ; i < reorder.length ; i++) { 541 adjustedReorder[i + 1] = reorder[i] + 1; 542 } 543 for (int i = 0 ; i < numTrailingArgs ; i++) { 544 adjustedReorder[i + reorder.length + 1] = i + newCoordinates.size() + 1; 545 } 546 return adjustedReorder; 547 } 548 549 private static MethodType methodTypeFor(VarHandle.AccessType at, MethodType oldType, List<Class<?>> oldCoordinates, List<Class<?>> newCoordinates) { 550 int numTrailingArgs = numTrailingArgs(at); 551 MethodType adjustedType = MethodType.methodType(oldType.returnType(), oldType.parameterType(0)); 552 adjustedType = adjustedType.appendParameterTypes(newCoordinates); 553 for (int i = 0 ; i < numTrailingArgs ; i++) { 554 adjustedType = adjustedType.appendParameterTypes(oldType.parameterType(1 + oldCoordinates.size() + i)); 555 } 556 return adjustedType; 557 } 558 559 public static VarHandle collectCoordinates(VarHandle target, int pos, MethodHandle pFilter) { 560 Objects.requireNonNull(target); 561 Objects.requireNonNull(pFilter); 562 MethodHandle filter = adaptForCheckedExceptions(pFilter); 563 564 List<Class<?>> targetCoordinates = target.coordinateTypes(); 565 if (pos < 0 || pos >= targetCoordinates.size()) { 566 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates); 567 } else if (filter.type().returnType() != void.class && filter.type().returnType() != targetCoordinates.get(pos)) { 568 throw newIllegalArgumentException("Invalid filter type " + filter.type() + " for coordinate type " + targetCoordinates.get(pos)); 569 } 570 571 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates); 572 if (filter.type().returnType() != void.class) { 573 newCoordinates.remove(pos); 574 } 575 newCoordinates.addAll(pos, filter.type().parameterList()); 576 577 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]), 578 (mode, modeHandle) -> MethodHandles.collectArguments(modeHandle, 1 + pos, filter)); 579 } 580 581 public static VarHandle dropCoordinates(VarHandle target, int pos, Class<?>... valueTypes) { 582 Objects.requireNonNull(target); 583 Objects.requireNonNull(valueTypes); 584 585 List<Class<?>> targetCoordinates = target.coordinateTypes(); 586 if (pos < 0 || pos > targetCoordinates.size()) { 587 throw newIllegalArgumentException("Invalid position " + pos + " for coordinate types", targetCoordinates); 588 } 589 590 if (valueTypes.length == 0) return target; 591 592 List<Class<?>> newCoordinates = new ArrayList<>(targetCoordinates); 593 newCoordinates.addAll(pos, List.of(valueTypes)); 594 595 return new IndirectVarHandle(target, target.varType(), newCoordinates.toArray(new Class<?>[0]), 596 (mode, modeHandle) -> MethodHandles.dropArguments(modeHandle, 1 + pos, valueTypes)); 597 } 598 599 private static MethodHandle adaptForCheckedExceptions(MethodHandle target) { 600 Class<?>[] exceptionTypes = exceptionTypes(target); 601 if (exceptionTypes != null) { // exceptions known 602 if (Stream.of(exceptionTypes).anyMatch(VarHandles::isCheckedException)) { 603 throw newIllegalArgumentException("Cannot adapt a var handle with a method handle which throws checked exceptions"); 604 } 605 return target; // no adaptation needed 606 } else { 607 MethodHandle handler = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_VarHandles_handleCheckedExceptions); 608 MethodHandle zero = MethodHandles.zero(target.type().returnType()); // dead branch 609 handler = MethodHandles.collectArguments(zero, 0, handler); 610 return MethodHandles.catchException(target, Throwable.class, handler); 611 } 612 } 613 614 static void handleCheckedExceptions(Throwable throwable) throws Throwable { 615 if (isCheckedException(throwable.getClass())) { 616 throw new IllegalStateException("Adapter handle threw checked exception", throwable); 617 } 618 throw throwable; 619 } 620 621 static Class<?>[] exceptionTypes(MethodHandle handle) { 622 if (handle instanceof DirectMethodHandle directHandle) { 623 byte refKind = directHandle.member.getReferenceKind(); 624 MethodHandleInfo info = new InfoFromMemberName( 625 MethodHandles.Lookup.IMPL_LOOKUP, 626 directHandle.member, 627 refKind); 628 if (MethodHandleNatives.refKindIsMethod(refKind)) { 629 return info.reflectAs(Method.class, MethodHandles.Lookup.IMPL_LOOKUP) 630 .getExceptionTypes(); 631 } else if (MethodHandleNatives.refKindIsField(refKind)) { 632 return new Class<?>[0]; 633 } else if (MethodHandleNatives.refKindIsConstructor(refKind)) { 634 return info.reflectAs(Constructor.class, MethodHandles.Lookup.IMPL_LOOKUP) 635 .getExceptionTypes(); 636 } else { 637 throw new AssertionError("Cannot get here"); 638 } 639 } else if (handle instanceof DelegatingMethodHandle delegatingMh) { 640 return exceptionTypes(delegatingMh.getTarget()); 641 } else if (handle instanceof NativeMethodHandle) { 642 return new Class<?>[0]; 643 } 644 645 assert handle instanceof BoundMethodHandle : "Unexpected handle type: " + handle; 646 // unknown 647 return null; 648 } 649 650 private static boolean isCheckedException(Class<?> clazz) { 651 return Throwable.class.isAssignableFrom(clazz) && 652 !RuntimeException.class.isAssignableFrom(clazz) && 653 !Error.class.isAssignableFrom(clazz); 654 } 655 656 // /** 657 // * A helper program to generate the VarHandleGuards class with a set of 658 // * static guard methods each of which corresponds to a particular shape and 659 // * performs a type check of the symbolic type descriptor with the VarHandle 660 // * type descriptor before linking/invoking to the underlying operation as 661 // * characterized by the operation member name on the VarForm of the 662 // * VarHandle. 663 // * <p> 664 // * The generated class essentially encapsulates pre-compiled LambdaForms, 665 // * one for each method, for the most set of common method signatures. 666 // * This reduces static initialization costs, footprint costs, and circular 667 // * dependencies that may arise if a class is generated per LambdaForm. 668 // * <p> 669 // * A maximum of L*T*S methods will be generated where L is the number of 670 // * access modes kinds (or unique operation signatures) and T is the number 671 // * of variable types and S is the number of shapes (such as instance field, 672 // * static field, or array access). 673 // * If there are 4 unique operation signatures, 5 basic types (Object, int, 674 // * long, float, double), and 3 shapes then a maximum of 60 methods will be 675 // * generated. However, the number is likely to be less since there 676 // * be duplicate signatures. 677 // * <p> 678 // * Each method is annotated with @LambdaForm.Compiled to inform the runtime 679 // * that such methods should be treated as if a method of a class that is the 680 // * result of compiling a LambdaForm. Annotation of such methods is 681 // * important for correct evaluation of certain assertions and method return 682 // * type profiling in HotSpot. 683 // */ 684 // public static class GuardMethodGenerator { 685 // 686 // static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)"; 687 // 688 // static final String GUARD_METHOD_TEMPLATE = 689 // """ 690 // @ForceInline 691 // @LambdaForm.Compiled 692 // @Hidden 693 // static final <METHOD> throws Throwable { 694 // boolean direct = handle.checkAccessModeThenIsDirect(ad); 695 // if (direct && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) { 696 // <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED> 697 // } else { 698 // MethodHandle mh = handle.getMethodHandle(ad.mode); 699 // <RETURN>mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>); 700 // } 701 // }"""; 702 // 703 // static final String GUARD_METHOD_TEMPLATE_V = 704 // """ 705 // @ForceInline 706 // @LambdaForm.Compiled 707 // @Hidden 708 // static final <METHOD> throws Throwable { 709 // boolean direct = handle.checkAccessModeThenIsDirect(ad); 710 // if (direct && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) { 711 // MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>); 712 // } else if (direct && handle.vform.getMethodType_V(ad.type) == ad.symbolicMethodTypeErased) { 713 // MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>); 714 // } else { 715 // MethodHandle mh = handle.getMethodHandle(ad.mode); 716 // mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>); 717 // } 718 // }"""; 719 // 720 // // A template for deriving the operations 721 // // could be supported by annotating VarHandle directly with the 722 // // operation kind and shape 723 // interface VarHandleTemplate { 724 // Object get(); 725 // 726 // void set(Object value); 727 // 728 // boolean compareAndSet(Object actualValue, Object expectedValue); 729 // 730 // Object compareAndExchange(Object actualValue, Object expectedValue); 731 // 732 // Object getAndUpdate(Object value); 733 // } 734 // 735 // record HandleType(Class<?> receiver, Class<?> value, Class<?>... intermediates) { 736 // } 737 // 738 // /** 739 // * @param args parameters 740 // */ 741 // public static void main(String[] args) { 742 // System.out.println("package java.lang.invoke;"); 743 // System.out.println(); 744 // System.out.println("import jdk.internal.vm.annotation.ForceInline;"); 745 // System.out.println("import jdk.internal.vm.annotation.Hidden;"); 746 // System.out.println(); 747 // System.out.println("// This class is auto-generated by " + 748 // GuardMethodGenerator.class.getName() + 749 // ". Do not edit."); 750 // System.out.println("final class VarHandleGuards {"); 751 // 752 // System.out.println(); 753 // 754 // // Declare the stream of shapes 755 // Stream<HandleType> hts = Stream.of( 756 // // Object->Object 757 // new HandleType(Object.class, Object.class), 758 // // Object->int 759 // new HandleType(Object.class, int.class), 760 // // Object->long 761 // new HandleType(Object.class, long.class), 762 // // Object->float 763 // new HandleType(Object.class, float.class), 764 // // Object->double 765 // new HandleType(Object.class, double.class), 766 // 767 // // <static>->Object 768 // new HandleType(null, Object.class), 769 // // <static>->int 770 // new HandleType(null, int.class), 771 // // <static>->long 772 // new HandleType(null, long.class), 773 // // <static>->float 774 // new HandleType(null, float.class), 775 // // <static>->double 776 // new HandleType(null, double.class), 777 // 778 // // Array[int]->Object 779 // new HandleType(Object.class, Object.class, int.class), 780 // // Array[int]->int 781 // new HandleType(Object.class, int.class, int.class), 782 // // Array[int]->long 783 // new HandleType(Object.class, long.class, int.class), 784 // // Array[int]->float 785 // new HandleType(Object.class, float.class, int.class), 786 // // Array[int]->double 787 // new HandleType(Object.class, double.class, int.class), 788 // 789 // // Array[long]->int 790 // new HandleType(Object.class, int.class, long.class), 791 // // Array[long]->long 792 // new HandleType(Object.class, long.class, long.class) 793 // ); 794 // 795 // hts.flatMap(ht -> Stream.of(VarHandleTemplate.class.getMethods()). 796 // map(m -> generateMethodType(m, ht.receiver, ht.value, ht.intermediates))). 797 // distinct(). 798 // map(GuardMethodGenerator::generateMethod). 799 // forEach(System.out::println); 800 // 801 // System.out.println("}"); 802 // } 803 // 804 // static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) { 805 // Class<?> returnType = m.getReturnType() == Object.class 806 // ? value : m.getReturnType(); 807 // 808 // List<Class<?>> params = new ArrayList<>(); 809 // if (receiver != null) 810 // params.add(receiver); 811 // java.util.Collections.addAll(params, intermediates); 812 // for (var p : m.getParameters()) { 813 // params.add(value); 814 // } 815 // return MethodType.methodType(returnType, params); 816 // } 817 // 818 // static String generateMethod(MethodType mt) { 819 // Class<?> returnType = mt.returnType(); 820 // 821 // var params = new java.util.LinkedHashMap<String, Class<?>>(); 822 // params.put("handle", VarHandle.class); 823 // for (int i = 0; i < mt.parameterCount(); i++) { 824 // params.put("arg" + i, mt.parameterType(i)); 825 // } 826 // params.put("ad", VarHandle.AccessDescriptor.class); 827 // 828 // // Generate method signature line 829 // String RETURN = className(returnType); 830 // String NAME = "guard"; 831 // String SIGNATURE = getSignature(mt); 832 // String PARAMS = params.entrySet().stream(). 833 // map(e -> className(e.getValue()) + " " + e.getKey()). 834 // collect(java.util.stream.Collectors.joining(", ")); 835 // String METHOD = GUARD_METHOD_SIG_TEMPLATE. 836 // replace("<RETURN>", RETURN). 837 // replace("<NAME>", NAME). 838 // replace("<SIGNATURE>", SIGNATURE). 839 // replace("<PARAMS>", PARAMS); 840 // 841 // // Generate method 842 // params.remove("ad"); 843 // 844 // List<String> LINK_TO_STATIC_ARGS = new ArrayList<>(params.keySet()); 845 // LINK_TO_STATIC_ARGS.add("handle.vform.getMemberName(ad.mode)"); 846 // 847 // List<String> LINK_TO_INVOKER_ARGS = new ArrayList<>(params.keySet()); 848 // LINK_TO_INVOKER_ARGS.set(0, LINK_TO_INVOKER_ARGS.get(0) + ".asDirect()"); 849 // 850 // RETURN = returnType == void.class 851 // ? "" 852 // : returnType == Object.class 853 // ? "return " 854 // : "return (" + returnType.getName() + ") "; 855 // 856 // String RESULT_ERASED = returnType == void.class 857 // ? "" 858 // : returnType != Object.class 859 // ? "return (" + returnType.getName() + ") " 860 // : "Object r = "; 861 // 862 // String RETURN_ERASED = returnType != Object.class 863 // ? "" 864 // : "\n return ad.returnType.cast(r);"; 865 // 866 // String template = returnType == void.class 867 // ? GUARD_METHOD_TEMPLATE_V 868 // : GUARD_METHOD_TEMPLATE; 869 // return template. 870 // replace("<METHOD>", METHOD). 871 // replace("<NAME>", NAME). 872 // replaceAll("<RETURN>", RETURN). 873 // replace("<RESULT_ERASED>", RESULT_ERASED). 874 // replace("<RETURN_ERASED>", RETURN_ERASED). 875 // replaceAll("<LINK_TO_STATIC_ARGS>", String.join(", ", LINK_TO_STATIC_ARGS)). 876 // replace("<LINK_TO_INVOKER_ARGS>", String.join(", ", LINK_TO_INVOKER_ARGS)) 877 // .indent(4); 878 // } 879 // 880 // static String className(Class<?> c) { 881 // String n = c.getName(); 882 // if (n.startsWith("java.lang.")) { 883 // n = n.replace("java.lang.", ""); 884 // if (n.startsWith("invoke.")) { 885 // n = n.replace("invoke.", ""); 886 // } 887 // } 888 // return n.replace('$', '.'); 889 // } 890 // 891 // static String getSignature(MethodType m) { 892 // StringBuilder sb = new StringBuilder(m.parameterCount() + 1); 893 // 894 // for (int i = 0; i < m.parameterCount(); i++) { 895 // Class<?> pt = m.parameterType(i); 896 // sb.append(getCharType(pt)); 897 // } 898 // 899 // sb.append('_').append(getCharType(m.returnType())); 900 // 901 // return sb.toString(); 902 // } 903 // 904 // static char getCharType(Class<?> pt) { 905 // return Wrapper.forBasicType(pt).basicTypeChar(); 906 // } 907 // } 908 }