1 /* 2 * Copyright (c) 2014, 2017, 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 static java.lang.invoke.MethodHandleStatics.UNSAFE; 29 30 final class VarHandles { 31 32 static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) { 33 if (!f.isStatic()) { 34 long foffset = MethodHandleNatives.objectFieldOffset(f); 35 if (!type.isPrimitive()) { 36 if (f.isFlatValue()) { 37 return f.isFinal() && !isWriteAllowedOnFinalFields 38 ? new VarHandleObjects.FlatValueFieldInstanceReadOnly(refc, foffset, type) 39 : new VarHandleObjects.FlatValueFieldInstanceReadWrite(refc, foffset, type); 40 } else { 41 return f.isFinal() && !isWriteAllowedOnFinalFields 42 ? new VarHandleObjects.FieldInstanceReadOnly(refc, foffset, type) 43 : new VarHandleObjects.FieldInstanceReadWrite(refc, foffset, type, f.canBeNull()); 44 } 45 } 46 else if (type == boolean.class) { 47 return f.isFinal() && !isWriteAllowedOnFinalFields 48 ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset) 49 : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset); 50 } 51 else if (type == byte.class) { 52 return f.isFinal() && !isWriteAllowedOnFinalFields 53 ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset) 54 : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset); 55 } 56 else if (type == short.class) { 57 return f.isFinal() && !isWriteAllowedOnFinalFields 58 ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset) 59 : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset); 60 } 61 else if (type == char.class) { 62 return f.isFinal() && !isWriteAllowedOnFinalFields 63 ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset) 64 : new VarHandleChars.FieldInstanceReadWrite(refc, foffset); 65 } 66 else if (type == int.class) { 67 return f.isFinal() && !isWriteAllowedOnFinalFields 68 ? new VarHandleInts.FieldInstanceReadOnly(refc, foffset) 69 : new VarHandleInts.FieldInstanceReadWrite(refc, foffset); 70 } 71 else if (type == long.class) { 72 return f.isFinal() && !isWriteAllowedOnFinalFields 73 ? new VarHandleLongs.FieldInstanceReadOnly(refc, foffset) 74 : new VarHandleLongs.FieldInstanceReadWrite(refc, foffset); 75 } 76 else if (type == float.class) { 77 return f.isFinal() && !isWriteAllowedOnFinalFields 78 ? new VarHandleFloats.FieldInstanceReadOnly(refc, foffset) 79 : new VarHandleFloats.FieldInstanceReadWrite(refc, foffset); 80 } 81 else if (type == double.class) { 82 return f.isFinal() && !isWriteAllowedOnFinalFields 83 ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset) 84 : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset); 85 } 86 else { 87 throw new UnsupportedOperationException(); 88 } 89 } 90 else { 91 // TODO This is not lazy on first invocation 92 // and might cause some circular initialization issues 93 94 // Replace with something similar to direct method handles 95 // where a barrier is used then elided after use 96 97 if (UNSAFE.shouldBeInitialized(refc)) 98 UNSAFE.ensureClassInitialized(refc); 99 100 Object base = MethodHandleNatives.staticFieldBase(f); 101 long foffset = MethodHandleNatives.staticFieldOffset(f); 102 if (!type.isPrimitive()) { 103 assert(!f.isFlatValue()); // static field is not flattened 104 return f.isFinal() && !isWriteAllowedOnFinalFields 105 ? new VarHandleObjects.FieldStaticReadOnly(base, foffset, type) 106 : new VarHandleObjects.FieldStaticReadWrite(base, foffset, type, f.canBeNull()); 107 } 108 else if (type == boolean.class) { 109 return f.isFinal() && !isWriteAllowedOnFinalFields 110 ? new VarHandleBooleans.FieldStaticReadOnly(base, foffset) 111 : new VarHandleBooleans.FieldStaticReadWrite(base, foffset); 112 } 113 else if (type == byte.class) { 114 return f.isFinal() && !isWriteAllowedOnFinalFields 115 ? new VarHandleBytes.FieldStaticReadOnly(base, foffset) 116 : new VarHandleBytes.FieldStaticReadWrite(base, foffset); 117 } 118 else if (type == short.class) { 119 return f.isFinal() && !isWriteAllowedOnFinalFields 120 ? new VarHandleShorts.FieldStaticReadOnly(base, foffset) 121 : new VarHandleShorts.FieldStaticReadWrite(base, foffset); 122 } 123 else if (type == char.class) { 124 return f.isFinal() && !isWriteAllowedOnFinalFields 125 ? new VarHandleChars.FieldStaticReadOnly(base, foffset) 126 : new VarHandleChars.FieldStaticReadWrite(base, foffset); 127 } 128 else if (type == int.class) { 129 return f.isFinal() && !isWriteAllowedOnFinalFields 130 ? new VarHandleInts.FieldStaticReadOnly(base, foffset) 131 : new VarHandleInts.FieldStaticReadWrite(base, foffset); 132 } 133 else if (type == long.class) { 134 return f.isFinal() && !isWriteAllowedOnFinalFields 135 ? new VarHandleLongs.FieldStaticReadOnly(base, foffset) 136 : new VarHandleLongs.FieldStaticReadWrite(base, foffset); 137 } 138 else if (type == float.class) { 139 return f.isFinal() && !isWriteAllowedOnFinalFields 140 ? new VarHandleFloats.FieldStaticReadOnly(base, foffset) 141 : new VarHandleFloats.FieldStaticReadWrite(base, foffset); 142 } 143 else if (type == double.class) { 144 return f.isFinal() && !isWriteAllowedOnFinalFields 145 ? new VarHandleDoubles.FieldStaticReadOnly(base, foffset) 146 : new VarHandleDoubles.FieldStaticReadWrite(base, foffset); 147 } 148 else { 149 throw new UnsupportedOperationException(); 150 } 151 } 152 } 153 154 static VarHandle makeArrayElementHandle(Class<?> arrayClass) { 155 if (!arrayClass.isArray()) 156 throw new IllegalArgumentException("not an array: " + arrayClass); 157 158 Class<?> componentType = arrayClass.getComponentType(); 159 160 int aoffset = UNSAFE.arrayBaseOffset(arrayClass); 161 int ascale = UNSAFE.arrayIndexScale(arrayClass); 162 int ashift = 31 - Integer.numberOfLeadingZeros(ascale); 163 164 if (!componentType.isPrimitive()) { 165 return componentType.isValue() 166 ? new VarHandleObjects.ValueArray(aoffset, ashift, arrayClass) 167 : new VarHandleObjects.Array(aoffset, ashift, arrayClass); 168 } 169 else if (componentType == boolean.class) { 170 return new VarHandleBooleans.Array(aoffset, ashift); 171 } 172 else if (componentType == byte.class) { 173 return new VarHandleBytes.Array(aoffset, ashift); 174 } 175 else if (componentType == short.class) { 176 return new VarHandleShorts.Array(aoffset, ashift); 177 } 178 else if (componentType == char.class) { 179 return new VarHandleChars.Array(aoffset, ashift); 180 } 181 else if (componentType == int.class) { 182 return new VarHandleInts.Array(aoffset, ashift); 183 } 184 else if (componentType == long.class) { 185 return new VarHandleLongs.Array(aoffset, ashift); 186 } 187 else if (componentType == float.class) { 188 return new VarHandleFloats.Array(aoffset, ashift); 189 } 190 else if (componentType == double.class) { 191 return new VarHandleDoubles.Array(aoffset, ashift); 192 } 193 else { 194 throw new UnsupportedOperationException(); 195 } 196 } 197 198 static VarHandle byteArrayViewHandle(Class<?> viewArrayClass, 199 boolean be) { 200 if (!viewArrayClass.isArray()) 201 throw new IllegalArgumentException("not an array: " + viewArrayClass); 202 203 Class<?> viewComponentType = viewArrayClass.getComponentType(); 204 205 if (viewComponentType == long.class) { 206 return new VarHandleByteArrayAsLongs.ArrayHandle(be); 207 } 208 else if (viewComponentType == int.class) { 209 return new VarHandleByteArrayAsInts.ArrayHandle(be); 210 } 211 else if (viewComponentType == short.class) { 212 return new VarHandleByteArrayAsShorts.ArrayHandle(be); 213 } 214 else if (viewComponentType == char.class) { 215 return new VarHandleByteArrayAsChars.ArrayHandle(be); 216 } 217 else if (viewComponentType == double.class) { 218 return new VarHandleByteArrayAsDoubles.ArrayHandle(be); 219 } 220 else if (viewComponentType == float.class) { 221 return new VarHandleByteArrayAsFloats.ArrayHandle(be); 222 } 223 224 throw new UnsupportedOperationException(); 225 } 226 227 static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass, 228 boolean be) { 229 if (!viewArrayClass.isArray()) 230 throw new IllegalArgumentException("not an array: " + viewArrayClass); 231 232 Class<?> viewComponentType = viewArrayClass.getComponentType(); 233 234 if (viewComponentType == long.class) { 235 return new VarHandleByteArrayAsLongs.ByteBufferHandle(be); 236 } 237 else if (viewComponentType == int.class) { 238 return new VarHandleByteArrayAsInts.ByteBufferHandle(be); 239 } 240 else if (viewComponentType == short.class) { 241 return new VarHandleByteArrayAsShorts.ByteBufferHandle(be); 242 } 243 else if (viewComponentType == char.class) { 244 return new VarHandleByteArrayAsChars.ByteBufferHandle(be); 245 } 246 else if (viewComponentType == double.class) { 247 return new VarHandleByteArrayAsDoubles.ByteBufferHandle(be); 248 } 249 else if (viewComponentType == float.class) { 250 return new VarHandleByteArrayAsFloats.ByteBufferHandle(be); 251 } 252 253 throw new UnsupportedOperationException(); 254 } 255 256 // /** 257 // * A helper program to generate the VarHandleGuards class with a set of 258 // * static guard methods each of which corresponds to a particular shape and 259 // * performs a type check of the symbolic type descriptor with the VarHandle 260 // * type descriptor before linking/invoking to the underlying operation as 261 // * characterized by the operation member name on the VarForm of the 262 // * VarHandle. 263 // * <p> 264 // * The generated class essentially encapsulates pre-compiled LambdaForms, 265 // * one for each method, for the most set of common method signatures. 266 // * This reduces static initialization costs, footprint costs, and circular 267 // * dependencies that may arise if a class is generated per LambdaForm. 268 // * <p> 269 // * A maximum of L*T*S methods will be generated where L is the number of 270 // * access modes kinds (or unique operation signatures) and T is the number 271 // * of variable types and S is the number of shapes (such as instance field, 272 // * static field, or array access). 273 // * If there are 4 unique operation signatures, 5 basic types (Object, int, 274 // * long, float, double), and 3 shapes then a maximum of 60 methods will be 275 // * generated. However, the number is likely to be less since there 276 // * be duplicate signatures. 277 // * <p> 278 // * Each method is annotated with @LambdaForm.Compiled to inform the runtime 279 // * that such methods should be treated as if a method of a class that is the 280 // * result of compiling a LambdaForm. Annotation of such methods is 281 // * important for correct evaluation of certain assertions and method return 282 // * type profiling in HotSpot. 283 // */ 284 // public static class GuardMethodGenerator { 285 // 286 // static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)"; 287 // 288 // static final String GUARD_METHOD_TEMPLATE = 289 // "@ForceInline\n" + 290 // "@LambdaForm.Compiled\n" + 291 // "final static <METHOD> throws Throwable {\n" + 292 // " if (handle.vform.methodType_table[ad.type] == ad.symbolicMethodType) {\n" + 293 // " <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED>\n" + 294 // " }\n" + 295 // " else {\n" + 296 // " MethodHandle mh = handle.getMethodHandle(ad.mode);\n" + 297 // " <RETURN>mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);\n" + 298 // " }\n" + 299 // "}"; 300 // 301 // static final String GUARD_METHOD_TEMPLATE_V = 302 // "@ForceInline\n" + 303 // "@LambdaForm.Compiled\n" + 304 // "final static <METHOD> throws Throwable {\n" + 305 // " if (handle.vform.methodType_table[ad.type] == ad.symbolicMethodType) {\n" + 306 // " MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);\n" + 307 // " }\n" + 308 // " else if (handle.vform.getMethodType_V(ad.type) == ad.symbolicMethodType) {\n" + 309 // " MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);\n" + 310 // " }\n" + 311 // " else {\n" + 312 // " MethodHandle mh = handle.getMethodHandle(ad.mode);\n" + 313 // " mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);\n" + 314 // " }\n" + 315 // "}"; 316 // 317 // // A template for deriving the operations 318 // // could be supported by annotating VarHandle directly with the 319 // // operation kind and shape 320 // interface VarHandleTemplate { 321 // Object get(); 322 // 323 // void set(Object value); 324 // 325 // boolean compareAndSet(Object actualValue, Object expectedValue); 326 // 327 // Object compareAndExchange(Object actualValue, Object expectedValue); 328 // 329 // Object getAndUpdate(Object value); 330 // } 331 // 332 // static class HandleType { 333 // final Class<?> receiver; 334 // final Class<?>[] intermediates; 335 // final Class<?> value; 336 // 337 // HandleType(Class<?> receiver, Class<?> value, Class<?>... intermediates) { 338 // this.receiver = receiver; 339 // this.intermediates = intermediates; 340 // this.value = value; 341 // } 342 // } 343 // 344 // /** 345 // * @param args parameters 346 // */ 347 // public static void main(String[] args) { 348 // System.out.println("package java.lang.invoke;"); 349 // System.out.println(); 350 // System.out.println("import jdk.internal.vm.annotation.ForceInline;"); 351 // System.out.println(); 352 // System.out.println("// This class is auto-generated by " + 353 // GuardMethodGenerator.class.getName() + 354 // ". Do not edit."); 355 // System.out.println("final class VarHandleGuards {"); 356 // 357 // System.out.println(); 358 // 359 // // Declare the stream of shapes 360 // Stream<HandleType> hts = Stream.of( 361 // // Object->Object 362 // new HandleType(Object.class, Object.class), 363 // // Object->int 364 // new HandleType(Object.class, int.class), 365 // // Object->long 366 // new HandleType(Object.class, long.class), 367 // // Object->float 368 // new HandleType(Object.class, float.class), 369 // // Object->double 370 // new HandleType(Object.class, double.class), 371 // 372 // // <static>->Object 373 // new HandleType(null, Object.class), 374 // // <static>->int 375 // new HandleType(null, int.class), 376 // // <static>->long 377 // new HandleType(null, long.class), 378 // // <static>->float 379 // new HandleType(null, float.class), 380 // // <static>->double 381 // new HandleType(null, double.class), 382 // 383 // // Array[int]->Object 384 // new HandleType(Object.class, Object.class, int.class), 385 // // Array[int]->int 386 // new HandleType(Object.class, int.class, int.class), 387 // // Array[int]->long 388 // new HandleType(Object.class, long.class, int.class), 389 // // Array[int]->float 390 // new HandleType(Object.class, float.class, int.class), 391 // // Array[int]->double 392 // new HandleType(Object.class, double.class, int.class), 393 // 394 // // Array[long]->int 395 // new HandleType(Object.class, int.class, long.class), 396 // // Array[long]->long 397 // new HandleType(Object.class, long.class, long.class) 398 // ); 399 // 400 // hts.flatMap(ht -> Stream.of(VarHandleTemplate.class.getMethods()). 401 // map(m -> generateMethodType(m, ht.receiver, ht.value, ht.intermediates))). 402 // distinct(). 403 // map(mt -> generateMethod(mt)). 404 // forEach(s -> { 405 // System.out.println(s); 406 // System.out.println(); 407 // }); 408 // 409 // System.out.println("}"); 410 // } 411 // 412 // static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) { 413 // Class<?> returnType = m.getReturnType() == Object.class 414 // ? value : m.getReturnType(); 415 // 416 // List<Class<?>> params = new ArrayList<>(); 417 // if (receiver != null) 418 // params.add(receiver); 419 // for (int i = 0; i < intermediates.length; i++) { 420 // params.add(intermediates[i]); 421 // } 422 // for (Parameter p : m.getParameters()) { 423 // params.add(value); 424 // } 425 // return MethodType.methodType(returnType, params); 426 // } 427 // 428 // static String generateMethod(MethodType mt) { 429 // Class<?> returnType = mt.returnType(); 430 // 431 // LinkedHashMap<String, Class<?>> params = new LinkedHashMap<>(); 432 // params.put("handle", VarHandle.class); 433 // for (int i = 0; i < mt.parameterCount(); i++) { 434 // params.put("arg" + i, mt.parameterType(i)); 435 // } 436 // params.put("ad", VarHandle.AccessDescriptor.class); 437 // 438 // // Generate method signature line 439 // String RETURN = className(returnType); 440 // String NAME = "guard"; 441 // String SIGNATURE = getSignature(mt); 442 // String PARAMS = params.entrySet().stream(). 443 // map(e -> className(e.getValue()) + " " + e.getKey()). 444 // collect(joining(", ")); 445 // String METHOD = GUARD_METHOD_SIG_TEMPLATE. 446 // replace("<RETURN>", RETURN). 447 // replace("<NAME>", NAME). 448 // replace("<SIGNATURE>", SIGNATURE). 449 // replace("<PARAMS>", PARAMS); 450 // 451 // // Generate method 452 // params.remove("ad"); 453 // 454 // List<String> LINK_TO_STATIC_ARGS = params.keySet().stream(). 455 // collect(toList()); 456 // LINK_TO_STATIC_ARGS.add("handle.vform.getMemberName(ad.mode)"); 457 // List<String> LINK_TO_STATIC_ARGS_V = params.keySet().stream(). 458 // collect(toList()); 459 // LINK_TO_STATIC_ARGS_V.add("handle.vform.getMemberName_V(ad.mode)"); 460 // 461 // List<String> LINK_TO_INVOKER_ARGS = params.keySet().stream(). 462 // collect(toList()); 463 // 464 // RETURN = returnType == void.class 465 // ? "" 466 // : returnType == Object.class 467 // ? "return " 468 // : "return (" + returnType.getName() + ") "; 469 // 470 // String RESULT_ERASED = returnType == void.class 471 // ? "" 472 // : returnType != Object.class 473 // ? "return (" + returnType.getName() + ") " 474 // : "Object r = "; 475 // 476 // String RETURN_ERASED = returnType != Object.class 477 // ? "" 478 // : " return ad.returnType.cast(r);"; 479 // 480 // String template = returnType == void.class 481 // ? GUARD_METHOD_TEMPLATE_V 482 // : GUARD_METHOD_TEMPLATE; 483 // return template. 484 // replace("<METHOD>", METHOD). 485 // replace("<NAME>", NAME). 486 // replaceAll("<RETURN>", RETURN). 487 // replace("<RESULT_ERASED>", RESULT_ERASED). 488 // replace("<RETURN_ERASED>", RETURN_ERASED). 489 // replaceAll("<LINK_TO_STATIC_ARGS>", LINK_TO_STATIC_ARGS.stream(). 490 // collect(joining(", "))). 491 // replaceAll("<LINK_TO_STATIC_ARGS_V>", LINK_TO_STATIC_ARGS_V.stream(). 492 // collect(joining(", "))). 493 // replace("<LINK_TO_INVOKER_ARGS>", LINK_TO_INVOKER_ARGS.stream(). 494 // collect(joining(", "))) 495 // ; 496 // } 497 // 498 // static String className(Class<?> c) { 499 // String n = c.getName(); 500 // if (n.startsWith("java.lang.")) { 501 // n = n.replace("java.lang.", ""); 502 // if (n.startsWith("invoke.")) { 503 // n = n.replace("invoke.", ""); 504 // } 505 // } 506 // return n.replace('$', '.'); 507 // } 508 // 509 // static String getSignature(MethodType m) { 510 // StringBuilder sb = new StringBuilder(m.parameterCount() + 1); 511 // 512 // for (int i = 0; i < m.parameterCount(); i++) { 513 // Class<?> pt = m.parameterType(i); 514 // sb.append(getCharType(pt)); 515 // } 516 // 517 // sb.append('_').append(getCharType(m.returnType())); 518 // 519 // return sb.toString(); 520 // } 521 // 522 // static char getCharType(Class<?> pt) { 523 // if (pt == void.class) { 524 // return 'V'; 525 // } 526 // else if (!pt.isPrimitive()) { 527 // return 'L'; 528 // } 529 // else if (pt == boolean.class) { 530 // return 'Z'; 531 // } 532 // else if (pt == int.class) { 533 // return 'I'; 534 // } 535 // else if (pt == long.class) { 536 // return 'J'; 537 // } 538 // else if (pt == float.class) { 539 // return 'F'; 540 // } 541 // else if (pt == double.class) { 542 // return 'D'; 543 // } 544 // else { 545 // throw new IllegalStateException(pt.getName()); 546 // } 547 // } 548 // } 549 }