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 661 // /** 662 // * A helper program to generate the VarHandleGuards class with a set of 663 // * static guard methods each of which corresponds to a particular shape and 664 // * performs a type check of the symbolic type descriptor with the VarHandle 665 // * type descriptor before linking/invoking to the underlying operation as 666 // * characterized by the operation member name on the VarForm of the 667 // * VarHandle. 668 // * <p> 669 // * The generated class essentially encapsulates pre-compiled LambdaForms, 670 // * one for each method, for the most set of common method signatures. 671 // * This reduces static initialization costs, footprint costs, and circular 672 // * dependencies that may arise if a class is generated per LambdaForm. 673 // * <p> 674 // * A maximum of L*T*S methods will be generated where L is the number of 675 // * access modes kinds (or unique operation signatures) and T is the number 676 // * of variable types and S is the number of shapes (such as instance field, 677 // * static field, or array access). 678 // * If there are 4 unique operation signatures, 5 basic types (Object, int, 679 // * long, float, double), and 3 shapes then a maximum of 60 methods will be 680 // * generated. However, the number is likely to be less since there 681 // * be duplicate signatures. 682 // * <p> 683 // * Each method is annotated with @LambdaForm.Compiled to inform the runtime 684 // * that such methods should be treated as if a method of a class that is the 685 // * result of compiling a LambdaForm. Annotation of such methods is 686 // * important for correct evaluation of certain assertions and method return 687 // * type profiling in HotSpot. 688 // */ 689 // public static class GuardMethodGenerator { 690 // 691 // static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)"; 692 // 693 // static final String GUARD_METHOD_TEMPLATE = 694 // """ 695 // @ForceInline 696 // @LambdaForm.Compiled 697 // @Hidden 698 // static final <METHOD> throws Throwable { 699 // boolean direct = handle.checkAccessModeThenIsDirect(ad); 700 // if (direct && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) { 701 // <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED> 702 // } else { 703 // MethodHandle mh = handle.getMethodHandle(ad.mode); 704 // <RETURN>mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>); 705 // } 706 // }"""; 707 // 708 // static final String GUARD_METHOD_TEMPLATE_V = 709 // """ 710 // @ForceInline 711 // @LambdaForm.Compiled 712 // @Hidden 713 // static final <METHOD> throws Throwable { 714 // boolean direct = handle.checkAccessModeThenIsDirect(ad); 715 // if (direct && handle.vform.methodType_table[ad.type] == ad.symbolicMethodTypeErased) { 716 // MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>); 717 // } else if (direct && handle.vform.getMethodType_V(ad.type) == ad.symbolicMethodTypeErased) { 718 // MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>); 719 // } else { 720 // MethodHandle mh = handle.getMethodHandle(ad.mode); 721 // mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>); 722 // } 723 // }"""; 724 // 725 // // A template for deriving the operations 726 // // could be supported by annotating VarHandle directly with the 727 // // operation kind and shape 728 // interface VarHandleTemplate { 729 // Object get(); 730 // 731 // void set(Object value); 732 // 733 // boolean compareAndSet(Object actualValue, Object expectedValue); 734 // 735 // Object compareAndExchange(Object actualValue, Object expectedValue); 736 // 737 // Object getAndUpdate(Object value); 738 // } 739 // 740 // record HandleType(Class<?> receiver, Class<?>... intermediates) { 741 // } 742 // 743 // /** 744 // * @param args parameters 745 // */ 746 // public static void main(String[] args) { 747 // System.out.println("package java.lang.invoke;"); 748 // System.out.println(); 749 // System.out.println("import jdk.internal.vm.annotation.ForceInline;"); 750 // System.out.println("import jdk.internal.vm.annotation.Hidden;"); 751 // System.out.println(); 752 // System.out.println("// This class is auto-generated by " + 753 // GuardMethodGenerator.class.getName() + 754 // ". Do not edit."); 755 // System.out.println("final class VarHandleGuards {"); 756 // 757 // System.out.println(); 758 // 759 // // Declare the stream of shapes 760 // List<HandleType> hts = List.of( 761 // // Object->T 762 // new HandleType(Object.class), 763 // 764 // // <static>->T 765 // new HandleType(null), 766 // 767 // // Array[index]->T 768 // new HandleType(Object.class, int.class), 769 // 770 // // MS[base]->T 771 // new HandleType(Object.class, long.class), 772 // 773 // // MS[base][offset]->T 774 // new HandleType(Object.class, long.class, long.class) 775 // ); 776 // 777 // Stream.of(VarHandleTemplate.class.getMethods()).<MethodType> 778 // mapMulti((m, sink) -> { 779 // for (var ht : hts) { 780 // for (var bt : LambdaForm.BasicType.ARG_TYPES) { 781 // sink.accept(generateMethodType(m, ht.receiver, bt.btClass, ht.intermediates)); 782 // } 783 // } 784 // }). 785 // distinct(). 786 // map(GuardMethodGenerator::generateMethod). 787 // forEach(System.out::println); 788 // 789 // System.out.println("}"); 790 // } 791 // 792 // static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) { 793 // Class<?> returnType = m.getReturnType() == Object.class 794 // ? value : m.getReturnType(); 795 // 796 // List<Class<?>> params = new ArrayList<>(); 797 // if (receiver != null) 798 // params.add(receiver); 799 // java.util.Collections.addAll(params, intermediates); 800 // for (var p : m.getParameters()) { 801 // params.add(value); 802 // } 803 // return MethodType.methodType(returnType, params); 804 // } 805 // 806 // static String generateMethod(MethodType mt) { 807 // Class<?> returnType = mt.returnType(); 808 // 809 // var params = new java.util.LinkedHashMap<String, Class<?>>(); 810 // params.put("handle", VarHandle.class); 811 // for (int i = 0; i < mt.parameterCount(); i++) { 812 // params.put("arg" + i, mt.parameterType(i)); 813 // } 814 // params.put("ad", VarHandle.AccessDescriptor.class); 815 // 816 // // Generate method signature line 817 // String RETURN = className(returnType); 818 // String NAME = "guard"; 819 // String SIGNATURE = getSignature(mt); 820 // String PARAMS = params.entrySet().stream(). 821 // map(e -> className(e.getValue()) + " " + e.getKey()). 822 // collect(java.util.stream.Collectors.joining(", ")); 823 // String METHOD = GUARD_METHOD_SIG_TEMPLATE. 824 // replace("<RETURN>", RETURN). 825 // replace("<NAME>", NAME). 826 // replace("<SIGNATURE>", SIGNATURE). 827 // replace("<PARAMS>", PARAMS); 828 // 829 // // Generate method 830 // params.remove("ad"); 831 // 832 // List<String> LINK_TO_STATIC_ARGS = new ArrayList<>(params.keySet()); 833 // LINK_TO_STATIC_ARGS.add("handle.vform.getMemberName(ad.mode)"); 834 // 835 // List<String> LINK_TO_INVOKER_ARGS = new ArrayList<>(params.keySet()); 836 // LINK_TO_INVOKER_ARGS.set(0, LINK_TO_INVOKER_ARGS.get(0) + ".asDirect()"); 837 // 838 // RETURN = returnType == void.class 839 // ? "" 840 // : returnType == Object.class 841 // ? "return " 842 // : "return (" + returnType.getName() + ") "; 843 // 844 // String RESULT_ERASED = returnType == void.class 845 // ? "" 846 // : returnType != Object.class 847 // ? "return (" + returnType.getName() + ") " 848 // : "Object r = "; 849 // 850 // String RETURN_ERASED = returnType != Object.class 851 // ? "" 852 // : "\n return ad.returnType.cast(r);"; 853 // 854 // String template = returnType == void.class 855 // ? GUARD_METHOD_TEMPLATE_V 856 // : GUARD_METHOD_TEMPLATE; 857 // return template. 858 // replace("<METHOD>", METHOD). 859 // replace("<NAME>", NAME). 860 // replaceAll("<RETURN>", RETURN). 861 // replace("<RESULT_ERASED>", RESULT_ERASED). 862 // replace("<RETURN_ERASED>", RETURN_ERASED). 863 // replaceAll("<LINK_TO_STATIC_ARGS>", String.join(", ", LINK_TO_STATIC_ARGS)). 864 // replace("<LINK_TO_INVOKER_ARGS>", String.join(", ", LINK_TO_INVOKER_ARGS)) 865 // .indent(4); 866 // } 867 // 868 // static String className(Class<?> c) { 869 // String n = c.getName(); 870 // if (n.startsWith("java.lang.")) { 871 // n = n.replace("java.lang.", ""); 872 // if (n.startsWith("invoke.")) { 873 // n = n.replace("invoke.", ""); 874 // } 875 // } 876 // return n.replace('$', '.'); 877 // } 878 // 879 // static String getSignature(MethodType m) { 880 // StringBuilder sb = new StringBuilder(m.parameterCount() + 1); 881 // 882 // for (int i = 0; i < m.parameterCount(); i++) { 883 // Class<?> pt = m.parameterType(i); 884 // sb.append(getCharType(pt)); 885 // } 886 // 887 // sb.append('_').append(getCharType(m.returnType())); 888 // 889 // return sb.toString(); 890 // } 891 // 892 // static char getCharType(Class<?> pt) { 893 // return Wrapper.forBasicType(pt).basicTypeChar(); 894 // } 895 // } 896 }