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