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.isFlattened()) { 37 return f.isFinal() && !isWriteAllowedOnFinalFields 38 ? new VarHandleObjects.ValueFieldInstanceReadOnly(refc, foffset, type) 39 : new VarHandleObjects.ValueFieldInstanceReadWrite(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.isNullable()); 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.isFlattened()); // 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.isNullable()); 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 new VarHandleObjects.Array(aoffset, ashift, arrayClass); 166 } 167 else if (componentType == boolean.class) { 168 return new VarHandleBooleans.Array(aoffset, ashift); 169 } 170 else if (componentType == byte.class) { 171 return new VarHandleBytes.Array(aoffset, ashift); 172 } 173 else if (componentType == short.class) { 174 return new VarHandleShorts.Array(aoffset, ashift); 175 } 176 else if (componentType == char.class) { 177 return new VarHandleChars.Array(aoffset, ashift); 178 } 179 else if (componentType == int.class) { 180 return new VarHandleInts.Array(aoffset, ashift); 181 } 182 else if (componentType == long.class) { 183 return new VarHandleLongs.Array(aoffset, ashift); 184 } 185 else if (componentType == float.class) { 186 return new VarHandleFloats.Array(aoffset, ashift); 187 } 188 else if (componentType == double.class) { 189 return new VarHandleDoubles.Array(aoffset, ashift); 190 } 191 else { 192 throw new UnsupportedOperationException(); 193 } 194 } 195 196 static VarHandle byteArrayViewHandle(Class<?> viewArrayClass, 197 boolean be) { 198 if (!viewArrayClass.isArray()) 199 throw new IllegalArgumentException("not an array: " + viewArrayClass); 200 201 Class<?> viewComponentType = viewArrayClass.getComponentType(); 202 203 if (viewComponentType == long.class) { 204 return new VarHandleByteArrayAsLongs.ArrayHandle(be); 205 } 206 else if (viewComponentType == int.class) { 207 return new VarHandleByteArrayAsInts.ArrayHandle(be); 208 } 209 else if (viewComponentType == short.class) { 210 return new VarHandleByteArrayAsShorts.ArrayHandle(be); 211 } 212 else if (viewComponentType == char.class) { 213 return new VarHandleByteArrayAsChars.ArrayHandle(be); 214 } 215 else if (viewComponentType == double.class) { 216 return new VarHandleByteArrayAsDoubles.ArrayHandle(be); 217 } 218 else if (viewComponentType == float.class) { 219 return new VarHandleByteArrayAsFloats.ArrayHandle(be); 220 } 221 222 throw new UnsupportedOperationException(); 223 } 224 225 static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass, 226 boolean be) { 227 if (!viewArrayClass.isArray()) 228 throw new IllegalArgumentException("not an array: " + viewArrayClass); 229 230 Class<?> viewComponentType = viewArrayClass.getComponentType(); 231 232 if (viewComponentType == long.class) { 233 return new VarHandleByteArrayAsLongs.ByteBufferHandle(be); 234 } 235 else if (viewComponentType == int.class) { 236 return new VarHandleByteArrayAsInts.ByteBufferHandle(be); 237 } 238 else if (viewComponentType == short.class) { 239 return new VarHandleByteArrayAsShorts.ByteBufferHandle(be); 240 } 241 else if (viewComponentType == char.class) { 242 return new VarHandleByteArrayAsChars.ByteBufferHandle(be); 243 } 244 else if (viewComponentType == double.class) { 245 return new VarHandleByteArrayAsDoubles.ByteBufferHandle(be); 246 } 247 else if (viewComponentType == float.class) { 248 return new VarHandleByteArrayAsFloats.ByteBufferHandle(be); 249 } 250 251 throw new UnsupportedOperationException(); 252 } 253 254 // /** 255 // * A helper program to generate the VarHandleGuards class with a set of 256 // * static guard methods each of which corresponds to a particular shape and 257 // * performs a type check of the symbolic type descriptor with the VarHandle 258 // * type descriptor before linking/invoking to the underlying operation as 259 // * characterized by the operation member name on the VarForm of the 260 // * VarHandle. 261 // * <p> 262 // * The generated class essentially encapsulates pre-compiled LambdaForms, 263 // * one for each method, for the most set of common method signatures. 264 // * This reduces static initialization costs, footprint costs, and circular 265 // * dependencies that may arise if a class is generated per LambdaForm. 266 // * <p> 267 // * A maximum of L*T*S methods will be generated where L is the number of 268 // * access modes kinds (or unique operation signatures) and T is the number 269 // * of variable types and S is the number of shapes (such as instance field, 270 // * static field, or array access). 271 // * If there are 4 unique operation signatures, 5 basic types (Object, int, 272 // * long, float, double), and 3 shapes then a maximum of 60 methods will be 273 // * generated. However, the number is likely to be less since there 274 // * be duplicate signatures. 275 // * <p> 276 // * Each method is annotated with @LambdaForm.Compiled to inform the runtime 277 // * that such methods should be treated as if a method of a class that is the 278 // * result of compiling a LambdaForm. Annotation of such methods is 279 // * important for correct evaluation of certain assertions and method return 280 // * type profiling in HotSpot. 281 // */ 282 // public static class GuardMethodGenerator { 283 // 284 // static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)"; 285 // 286 // static final String GUARD_METHOD_TEMPLATE = 287 // "@ForceInline\n" + 288 // "@LambdaForm.Compiled\n" + 289 // "final static <METHOD> throws Throwable {\n" + 290 // " if (handle.vform.methodType_table[ad.type] == ad.symbolicMethodType) {\n" + 291 // " <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED>\n" + 292 // " }\n" + 293 // " else {\n" + 294 // " MethodHandle mh = handle.getMethodHandle(ad.mode);\n" + 295 // " <RETURN>mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);\n" + 296 // " }\n" + 297 // "}"; 298 // 299 // static final String GUARD_METHOD_TEMPLATE_V = 300 // "@ForceInline\n" + 301 // "@LambdaForm.Compiled\n" + 302 // "final static <METHOD> throws Throwable {\n" + 303 // " if (handle.vform.methodType_table[ad.type] == ad.symbolicMethodType) {\n" + 304 // " MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);\n" + 305 // " }\n" + 306 // " else if (handle.vform.getMethodType_V(ad.type) == ad.symbolicMethodType) {\n" + 307 // " MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);\n" + 308 // " }\n" + 309 // " else {\n" + 310 // " MethodHandle mh = handle.getMethodHandle(ad.mode);\n" + 311 // " mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);\n" + 312 // " }\n" + 313 // "}"; 314 // 315 // // A template for deriving the operations 316 // // could be supported by annotating VarHandle directly with the 317 // // operation kind and shape 318 // interface VarHandleTemplate { 319 // Object get(); 320 // 321 // void set(Object value); 322 // 323 // boolean compareAndSet(Object actualValue, Object expectedValue); 324 // 325 // Object compareAndExchange(Object actualValue, Object expectedValue); 326 // 327 // Object getAndUpdate(Object value); 328 // } 329 // 330 // static class HandleType { 331 // final Class<?> receiver; 332 // final Class<?>[] intermediates; 333 // final Class<?> value; 334 // 335 // HandleType(Class<?> receiver, Class<?> value, Class<?>... intermediates) { 336 // this.receiver = receiver; 337 // this.intermediates = intermediates; 338 // this.value = value; 339 // } 340 // } 341 // 342 // /** 343 // * @param args parameters 344 // */ 345 // public static void main(String[] args) { 346 // System.out.println("package java.lang.invoke;"); 347 // System.out.println(); 348 // System.out.println("import jdk.internal.vm.annotation.ForceInline;"); 349 // System.out.println(); 350 // System.out.println("// This class is auto-generated by " + 351 // GuardMethodGenerator.class.getName() + 352 // ". Do not edit."); 353 // System.out.println("final class VarHandleGuards {"); 354 // 355 // System.out.println(); 356 // 357 // // Declare the stream of shapes 358 // Stream<HandleType> hts = Stream.of( 359 // // Object->Object 360 // new HandleType(Object.class, Object.class), 361 // // Object->int 362 // new HandleType(Object.class, int.class), 363 // // Object->long 364 // new HandleType(Object.class, long.class), 365 // // Object->float 366 // new HandleType(Object.class, float.class), 367 // // Object->double 368 // new HandleType(Object.class, double.class), 369 // 370 // // <static>->Object 371 // new HandleType(null, Object.class), 372 // // <static>->int 373 // new HandleType(null, int.class), 374 // // <static>->long 375 // new HandleType(null, long.class), 376 // // <static>->float 377 // new HandleType(null, float.class), 378 // // <static>->double 379 // new HandleType(null, double.class), 380 // 381 // // Array[int]->Object 382 // new HandleType(Object.class, Object.class, int.class), 383 // // Array[int]->int 384 // new HandleType(Object.class, int.class, int.class), 385 // // Array[int]->long 386 // new HandleType(Object.class, long.class, int.class), 387 // // Array[int]->float 388 // new HandleType(Object.class, float.class, int.class), 389 // // Array[int]->double 390 // new HandleType(Object.class, double.class, int.class), 391 // 392 // // Array[long]->int 393 // new HandleType(Object.class, int.class, long.class), 394 // // Array[long]->long 395 // new HandleType(Object.class, long.class, long.class) 396 // ); 397 // 398 // hts.flatMap(ht -> Stream.of(VarHandleTemplate.class.getMethods()). 399 // map(m -> generateMethodType(m, ht.receiver, ht.value, ht.intermediates))). 400 // distinct(). 401 // map(mt -> generateMethod(mt)). 402 // forEach(s -> { 403 // System.out.println(s); 404 // System.out.println(); 405 // }); 406 // 407 // System.out.println("}"); 408 // } 409 // 410 // static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) { 411 // Class<?> returnType = m.getReturnType() == Object.class 412 // ? value : m.getReturnType(); 413 // 414 // List<Class<?>> params = new ArrayList<>(); 415 // if (receiver != null) 416 // params.add(receiver); 417 // for (int i = 0; i < intermediates.length; i++) { 418 // params.add(intermediates[i]); 419 // } 420 // for (Parameter p : m.getParameters()) { 421 // params.add(value); 422 // } 423 // return MethodType.methodType(returnType, params); 424 // } 425 // 426 // static String generateMethod(MethodType mt) { 427 // Class<?> returnType = mt.returnType(); 428 // 429 // LinkedHashMap<String, Class<?>> params = new LinkedHashMap<>(); 430 // params.put("handle", VarHandle.class); 431 // for (int i = 0; i < mt.parameterCount(); i++) { 432 // params.put("arg" + i, mt.parameterType(i)); 433 // } 434 // params.put("ad", VarHandle.AccessDescriptor.class); 435 // 436 // // Generate method signature line 437 // String RETURN = className(returnType); 438 // String NAME = "guard"; 439 // String SIGNATURE = getSignature(mt); 440 // String PARAMS = params.entrySet().stream(). 441 // map(e -> className(e.getValue()) + " " + e.getKey()). 442 // collect(joining(", ")); 443 // String METHOD = GUARD_METHOD_SIG_TEMPLATE. 444 // replace("<RETURN>", RETURN). 445 // replace("<NAME>", NAME). 446 // replace("<SIGNATURE>", SIGNATURE). 447 // replace("<PARAMS>", PARAMS); 448 // 449 // // Generate method 450 // params.remove("ad"); 451 // 452 // List<String> LINK_TO_STATIC_ARGS = params.keySet().stream(). 453 // collect(toList()); 454 // LINK_TO_STATIC_ARGS.add("handle.vform.getMemberName(ad.mode)"); 455 // List<String> LINK_TO_STATIC_ARGS_V = params.keySet().stream(). 456 // collect(toList()); 457 // LINK_TO_STATIC_ARGS_V.add("handle.vform.getMemberName_V(ad.mode)"); 458 // 459 // List<String> LINK_TO_INVOKER_ARGS = params.keySet().stream(). 460 // collect(toList()); 461 // 462 // RETURN = returnType == void.class 463 // ? "" 464 // : returnType == Object.class 465 // ? "return " 466 // : "return (" + returnType.getName() + ") "; 467 // 468 // String RESULT_ERASED = returnType == void.class 469 // ? "" 470 // : returnType != Object.class 471 // ? "return (" + returnType.getName() + ") " 472 // : "Object r = "; 473 // 474 // String RETURN_ERASED = returnType != Object.class 475 // ? "" 476 // : " return ad.returnType.cast(r);"; 477 // 478 // String template = returnType == void.class 479 // ? GUARD_METHOD_TEMPLATE_V 480 // : GUARD_METHOD_TEMPLATE; 481 // return template. 482 // replace("<METHOD>", METHOD). 483 // replace("<NAME>", NAME). 484 // replaceAll("<RETURN>", RETURN). 485 // replace("<RESULT_ERASED>", RESULT_ERASED). 486 // replace("<RETURN_ERASED>", RETURN_ERASED). 487 // replaceAll("<LINK_TO_STATIC_ARGS>", LINK_TO_STATIC_ARGS.stream(). 488 // collect(joining(", "))). 489 // replaceAll("<LINK_TO_STATIC_ARGS_V>", LINK_TO_STATIC_ARGS_V.stream(). 490 // collect(joining(", "))). 491 // replace("<LINK_TO_INVOKER_ARGS>", LINK_TO_INVOKER_ARGS.stream(). 492 // collect(joining(", "))) 493 // ; 494 // } 495 // 496 // static String className(Class<?> c) { 497 // String n = c.getName(); 498 // if (n.startsWith("java.lang.")) { 499 // n = n.replace("java.lang.", ""); 500 // if (n.startsWith("invoke.")) { 501 // n = n.replace("invoke.", ""); 502 // } 503 // } 504 // return n.replace('$', '.'); 505 // } 506 // 507 // static String getSignature(MethodType m) { 508 // StringBuilder sb = new StringBuilder(m.parameterCount() + 1); 509 // 510 // for (int i = 0; i < m.parameterCount(); i++) { 511 // Class<?> pt = m.parameterType(i); 512 // sb.append(getCharType(pt)); 513 // } 514 // 515 // sb.append('_').append(getCharType(m.returnType())); 516 // 517 // return sb.toString(); 518 // } 519 // 520 // static char getCharType(Class<?> pt) { 521 // if (pt == void.class) { 522 // return 'V'; 523 // } 524 // else if (!pt.isPrimitive()) { 525 // return 'L'; 526 // } 527 // else if (pt == boolean.class) { 528 // return 'Z'; 529 // } 530 // else if (pt == int.class) { 531 // return 'I'; 532 // } 533 // else if (pt == long.class) { 534 // return 'J'; 535 // } 536 // else if (pt == float.class) { 537 // return 'F'; 538 // } 539 // else if (pt == double.class) { 540 // return 'D'; 541 // } 542 // else { 543 // throw new IllegalStateException(pt.getName()); 544 // } 545 // } 546 // } 547 }