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