1 /* 2 * Copyright (c) 2017, 2022, 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.runtime; 27 28 import jdk.internal.value.PrimitiveClass; 29 30 import java.lang.invoke.ConstantCallSite; 31 import java.lang.invoke.MethodHandle; 32 import java.lang.invoke.MethodHandles; 33 import java.lang.invoke.MethodType; 34 import java.lang.invoke.StringConcatFactory; 35 import java.lang.invoke.TypeDescriptor; 36 import java.security.AccessController; 37 import java.security.PrivilegedAction; 38 import java.util.ArrayList; 39 import java.util.Arrays; 40 import java.util.HashMap; 41 import java.util.List; 42 import java.util.Objects; 43 44 import static java.util.Objects.requireNonNull; 45 46 /** 47 * Bootstrap methods for state-driven implementations of core methods, 48 * including {@link Object#equals(Object)}, {@link Object#hashCode()}, and 49 * {@link Object#toString()}. These methods may be used, for example, by 50 * Java compiler implementations to implement the bodies of {@link Object} 51 * methods for record classes. 52 * 53 * @since 16 54 */ 55 public class ObjectMethods { 56 57 private ObjectMethods() { } 58 59 private static final int MAX_STRING_CONCAT_SLOTS = 20; 60 61 private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class); 62 private static final MethodType NAMES_MT = MethodType.methodType(List.class); 63 private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false); 64 private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true); 65 private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0); 66 private static final MethodHandle CLASS_IS_INSTANCE; 67 private static final MethodHandle OBJECT_EQUALS; 68 private static final MethodHandle OBJECTS_EQUALS; 69 private static final MethodHandle OBJECTS_HASHCODE; 70 private static final MethodHandle OBJECTS_TOSTRING; 71 private static final MethodHandle OBJECT_EQ; 72 private static final MethodHandle OBJECT_HASHCODE; 73 private static final MethodHandle OBJECT_TO_STRING; 74 private static final MethodHandle STRING_FORMAT; 75 private static final MethodHandle HASH_COMBINER; 76 77 /* package-private */ 78 static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>(); 79 80 private static final HashMap<Class<?>, MethodHandle> primitiveHashers = new HashMap<>(); 81 private static final HashMap<Class<?>, MethodHandle> primitiveToString = new HashMap<>(); 82 83 static { 84 try { 85 Class<ObjectMethods> OBJECT_METHODS_CLASS = ObjectMethods.class; 86 MethodHandles.Lookup publicLookup = MethodHandles.publicLookup(); 87 MethodHandles.Lookup lookup = MethodHandles.lookup(); 88 89 @SuppressWarnings("removal") 90 ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { 91 @Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); } 92 }); 93 94 CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance", 95 MethodType.methodType(boolean.class, Object.class)); 96 OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals", 97 MethodType.methodType(boolean.class, Object.class)); 98 OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode", 99 MethodType.fromMethodDescriptorString("()I", loader)); 100 OBJECT_TO_STRING = publicLookup.findVirtual(Object.class, "toString", 101 MethodType.methodType(String.class)); 102 STRING_FORMAT = publicLookup.findStatic(String.class, "format", 103 MethodType.methodType(String.class, String.class, Object[].class)); 104 OBJECTS_EQUALS = publicLookup.findStatic(Objects.class, "equals", 105 MethodType.methodType(boolean.class, Object.class, Object.class)); 106 OBJECTS_HASHCODE = publicLookup.findStatic(Objects.class, "hashCode", 107 MethodType.methodType(int.class, Object.class)); 108 OBJECTS_TOSTRING = publicLookup.findStatic(Objects.class, "toString", 109 MethodType.methodType(String.class, Object.class)); 110 111 OBJECT_EQ = lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 112 MethodType.methodType(boolean.class, Object.class, Object.class)); 113 HASH_COMBINER = lookup.findStatic(OBJECT_METHODS_CLASS, "hashCombiner", 114 MethodType.fromMethodDescriptorString("(II)I", loader)); 115 116 primitiveEquals.put(byte.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 117 MethodType.fromMethodDescriptorString("(BB)Z", loader))); 118 primitiveEquals.put(short.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 119 MethodType.fromMethodDescriptorString("(SS)Z", loader))); 120 primitiveEquals.put(char.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 121 MethodType.fromMethodDescriptorString("(CC)Z", loader))); 122 primitiveEquals.put(int.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 123 MethodType.fromMethodDescriptorString("(II)Z", loader))); 124 primitiveEquals.put(long.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 125 MethodType.fromMethodDescriptorString("(JJ)Z", loader))); 126 primitiveEquals.put(float.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 127 MethodType.fromMethodDescriptorString("(FF)Z", loader))); 128 primitiveEquals.put(double.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 129 MethodType.fromMethodDescriptorString("(DD)Z", loader))); 130 primitiveEquals.put(boolean.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq", 131 MethodType.fromMethodDescriptorString("(ZZ)Z", loader))); 132 133 primitiveHashers.put(byte.class, lookup.findStatic(Byte.class, "hashCode", 134 MethodType.fromMethodDescriptorString("(B)I", loader))); 135 primitiveHashers.put(short.class, lookup.findStatic(Short.class, "hashCode", 136 MethodType.fromMethodDescriptorString("(S)I", loader))); 137 primitiveHashers.put(char.class, lookup.findStatic(Character.class, "hashCode", 138 MethodType.fromMethodDescriptorString("(C)I", loader))); 139 primitiveHashers.put(int.class, lookup.findStatic(Integer.class, "hashCode", 140 MethodType.fromMethodDescriptorString("(I)I", loader))); 141 primitiveHashers.put(long.class, lookup.findStatic(Long.class, "hashCode", 142 MethodType.fromMethodDescriptorString("(J)I", loader))); 143 primitiveHashers.put(float.class, lookup.findStatic(Float.class, "hashCode", 144 MethodType.fromMethodDescriptorString("(F)I", loader))); 145 primitiveHashers.put(double.class, lookup.findStatic(Double.class, "hashCode", 146 MethodType.fromMethodDescriptorString("(D)I", loader))); 147 primitiveHashers.put(boolean.class, lookup.findStatic(Boolean.class, "hashCode", 148 MethodType.fromMethodDescriptorString("(Z)I", loader))); 149 150 primitiveToString.put(byte.class, lookup.findStatic(Byte.class, "toString", 151 MethodType.methodType(String.class, byte.class))); 152 primitiveToString.put(short.class, lookup.findStatic(Short.class, "toString", 153 MethodType.methodType(String.class, short.class))); 154 primitiveToString.put(char.class, lookup.findStatic(Character.class, "toString", 155 MethodType.methodType(String.class, char.class))); 156 primitiveToString.put(int.class, lookup.findStatic(Integer.class, "toString", 157 MethodType.methodType(String.class, int.class))); 158 primitiveToString.put(long.class, lookup.findStatic(Long.class, "toString", 159 MethodType.methodType(String.class, long.class))); 160 primitiveToString.put(float.class, lookup.findStatic(Float.class, "toString", 161 MethodType.methodType(String.class, float.class))); 162 primitiveToString.put(double.class, lookup.findStatic(Double.class, "toString", 163 MethodType.methodType(String.class, double.class))); 164 primitiveToString.put(boolean.class, lookup.findStatic(Boolean.class, "toString", 165 MethodType.methodType(String.class, boolean.class))); 166 } 167 catch (ReflectiveOperationException e) { 168 throw new RuntimeException(e); 169 } 170 } 171 172 private static int hashCombiner(int x, int y) { 173 return x*31 + y; 174 } 175 176 private static boolean eq(Object a, Object b) { return a == b; } 177 private static boolean eq(byte a, byte b) { return a == b; } 178 private static boolean eq(short a, short b) { return a == b; } 179 private static boolean eq(char a, char b) { return a == b; } 180 private static boolean eq(int a, int b) { return a == b; } 181 private static boolean eq(long a, long b) { return a == b; } 182 private static boolean eq(float a, float b) { return Float.compare(a, b) == 0; } 183 private static boolean eq(double a, double b) { return Double.compare(a, b) == 0; } 184 private static boolean eq(boolean a, boolean b) { return a == b; } 185 186 /** Get the method handle for combining two values of a given type */ 187 private static MethodHandle equalator(Class<?> clazz) { 188 return (clazz.isPrimitive() 189 ? primitiveEquals.get(clazz) 190 : OBJECTS_EQUALS.asType(MethodType.methodType(boolean.class, clazz, clazz))); 191 } 192 193 /** Get the hasher for a value of a given type */ 194 private static MethodHandle hasher(Class<?> clazz) { 195 return (clazz.isPrimitive() 196 ? primitiveHashers.get(clazz) 197 : OBJECTS_HASHCODE.asType(MethodType.methodType(int.class, clazz))); 198 } 199 200 /** Get the stringifier for a value of a given type */ 201 private static MethodHandle stringifier(Class<?> clazz) { 202 return (clazz.isPrimitive() 203 ? primitiveToString.get(clazz) 204 : OBJECTS_TOSTRING.asType(MethodType.methodType(String.class, clazz))); 205 } 206 207 /** 208 * Generates a method handle for the {@code equals} method for a given data class 209 * @param receiverClass the data class 210 * @param getters the list of getters 211 * @return the method handle 212 */ 213 private static MethodHandle makeEquals(Class<?> receiverClass, 214 List<MethodHandle> getters) { 215 MethodType rr = MethodType.methodType(boolean.class, receiverClass, receiverClass); 216 MethodType ro = MethodType.methodType(boolean.class, receiverClass, Object.class); 217 MethodHandle instanceFalse = MethodHandles.dropArguments(FALSE, 0, receiverClass, Object.class); // (RO)Z 218 MethodHandle instanceTrue = MethodHandles.dropArguments(TRUE, 0, receiverClass, Object.class); // (RO)Z 219 MethodHandle isSameObject = OBJECT_EQ.asType(ro); // (RO)Z 220 MethodHandle isInstance = MethodHandles.dropArguments(CLASS_IS_INSTANCE.bindTo(receiverClass), 0, receiverClass); // (RO)Z 221 MethodHandle accumulator = MethodHandles.dropArguments(TRUE, 0, receiverClass, receiverClass); // (RR)Z 222 223 for (MethodHandle getter : getters) { 224 MethodHandle equalator = equalator(getter.type().returnType()); // (TT)Z 225 MethodHandle thisFieldEqual = MethodHandles.filterArguments(equalator, 0, getter, getter); // (RR)Z 226 accumulator = MethodHandles.guardWithTest(thisFieldEqual, accumulator, instanceFalse.asType(rr)); 227 } 228 229 return MethodHandles.guardWithTest(isSameObject, 230 instanceTrue, 231 MethodHandles.guardWithTest(isInstance, accumulator.asType(ro), instanceFalse)); 232 } 233 234 /** 235 * Generates a method handle for the {@code hashCode} method for a given data class 236 * @param receiverClass the data class 237 * @param getters the list of getters 238 * @return the method handle 239 */ 240 private static MethodHandle makeHashCode(Class<?> receiverClass, 241 List<MethodHandle> getters) { 242 MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I 243 244 // @@@ Use loop combinator instead? 245 for (MethodHandle getter : getters) { 246 MethodHandle hasher = hasher(getter.type().returnType()); // (T)I 247 MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter); // (R)I 248 MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I 249 accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I 250 } 251 252 return accumulator; 253 } 254 255 /** 256 * Generates a method handle for the {@code toString} method for a given data class 257 * @param receiverClass the data class 258 * @param simpleName the simple name of the record class 259 * @param getters the list of getters 260 * @param names the names 261 * @return the method handle 262 */ 263 private static MethodHandle makeToString(MethodHandles.Lookup lookup, 264 Class<?> receiverClass, 265 String simpleName, 266 MethodHandle[] getters, 267 List<String> names) { 268 assert getters.length == names.size(); 269 if (getters.length == 0) { 270 // special case 271 MethodHandle emptyRecordCase = MethodHandles.constant(String.class, simpleName + "[]"); 272 emptyRecordCase = MethodHandles.dropArguments(emptyRecordCase, 0, receiverClass); // (R)S 273 return emptyRecordCase; 274 } 275 276 boolean firstTime = true; 277 MethodHandle[] mhs; 278 List<List<MethodHandle>> splits; 279 MethodHandle[] toSplit = getters; 280 int namesIndex = 0; 281 do { 282 /* StringConcatFactory::makeConcatWithConstants can only deal with 200 slots, longs and double occupy two 283 * the rest 1 slot, we need to chop the current `getters` into chunks, it could be that for records with 284 * a lot of components that we need to do a couple of iterations. The main difference between the first 285 * iteration and the rest would be on the recipe 286 */ 287 splits = split(toSplit); 288 mhs = new MethodHandle[splits.size()]; 289 for (int splitIndex = 0; splitIndex < splits.size(); splitIndex++) { 290 String recipe = ""; 291 if (firstTime && splitIndex == 0) { 292 recipe = simpleName + "["; 293 } 294 for (int i = 0; i < splits.get(splitIndex).size(); i++) { 295 recipe += firstTime ? names.get(namesIndex) + "=" + "\1" : "\1"; 296 if (firstTime && namesIndex != names.size() - 1) { 297 recipe += ", "; 298 } 299 namesIndex++; 300 } 301 if (firstTime && splitIndex == splits.size() - 1) { 302 recipe += "]"; 303 } 304 Class<?>[] concatTypeArgs = new Class<?>[splits.get(splitIndex).size()]; 305 // special case: no need to create another getters if there is only one split 306 MethodHandle[] currentSplitGetters = new MethodHandle[splits.get(splitIndex).size()]; 307 for (int j = 0; j < splits.get(splitIndex).size(); j++) { 308 concatTypeArgs[j] = splits.get(splitIndex).get(j).type().returnType(); 309 currentSplitGetters[j] = splits.get(splitIndex).get(j); 310 } 311 MethodType concatMT = MethodType.methodType(String.class, concatTypeArgs); 312 try { 313 mhs[splitIndex] = StringConcatFactory.makeConcatWithConstants( 314 lookup, "", 315 concatMT, 316 recipe, 317 new Object[0] 318 ).getTarget(); 319 mhs[splitIndex] = MethodHandles.filterArguments(mhs[splitIndex], 0, currentSplitGetters); 320 // this will spread the receiver class across all the getters 321 mhs[splitIndex] = MethodHandles.permuteArguments( 322 mhs[splitIndex], 323 MethodType.methodType(String.class, receiverClass), 324 new int[splits.get(splitIndex).size()] 325 ); 326 } catch (Throwable t) { 327 throw new RuntimeException(t); 328 } 329 } 330 toSplit = mhs; 331 firstTime = false; 332 } while (splits.size() > 1); 333 return mhs[0]; 334 } 335 336 /** 337 * Chops the getters into smaller chunks according to the maximum number of slots 338 * StringConcatFactory::makeConcatWithConstants can chew 339 * @param getters the current getters 340 * @return chunks that won't surpass the maximum number of slots StringConcatFactory::makeConcatWithConstants can chew 341 */ 342 private static List<List<MethodHandle>> split(MethodHandle[] getters) { 343 List<List<MethodHandle>> splits = new ArrayList<>(); 344 345 int slots = 0; 346 347 // Need to peel, so that neither call has more than acceptable number 348 // of slots for the arguments. 349 List<MethodHandle> cArgs = new ArrayList<>(); 350 for (MethodHandle methodHandle : getters) { 351 Class<?> returnType = methodHandle.type().returnType(); 352 int needSlots = (returnType == long.class || returnType == double.class) ? 2 : 1; 353 if (slots + needSlots > MAX_STRING_CONCAT_SLOTS) { 354 splits.add(cArgs); 355 cArgs = new ArrayList<>(); 356 slots = 0; 357 } 358 cArgs.add(methodHandle); 359 slots += needSlots; 360 } 361 362 // Flush the tail slice 363 if (!cArgs.isEmpty()) { 364 splits.add(cArgs); 365 } 366 367 return splits; 368 } 369 370 /** 371 * Bootstrap method to generate the {@link Object#equals(Object)}, 372 * {@link Object#hashCode()}, and {@link Object#toString()} methods, based 373 * on a description of the component names and accessor methods, for either 374 * {@code invokedynamic} call sites or dynamic constant pool entries. 375 * 376 * For more detail on the semantics of the generated methods see the specification 377 * of {@link java.lang.Record#equals(Object)}, {@link java.lang.Record#hashCode()} and 378 * {@link java.lang.Record#toString()}. 379 * 380 * 381 * @param lookup Every bootstrap method is expected to have a {@code lookup} 382 * which usually represents a lookup context with the 383 * accessibility privileges of the caller. This is because 384 * {@code invokedynamic} call sites always provide a {@code lookup} 385 * to the corresponding bootstrap method, but this method just 386 * ignores the {@code lookup} parameter 387 * @param methodName the name of the method to generate, which must be one of 388 * {@code "equals"}, {@code "hashCode"}, or {@code "toString"} 389 * @param type a {@link MethodType} corresponding the descriptor type 390 * for the method, which must correspond to the descriptor 391 * for the corresponding {@link Object} method, if linking 392 * an {@code invokedynamic} call site, or the 393 * constant {@code MethodHandle.class}, if linking a 394 * dynamic constant 395 * @param recordClass the record class hosting the record components 396 * @param names the list of component names, joined into a string 397 * separated by ";", or the empty string if there are no 398 * components. This parameter is ignored if the {@code methodName} 399 * parameter is {@code "equals"} or {@code "hashCode"} 400 * @param getters method handles for the accessor methods for the components 401 * @return a call site if invoked by indy, or a method handle 402 * if invoked by a condy 403 * @throws IllegalArgumentException if the bootstrap arguments are invalid 404 * or inconsistent 405 * @throws NullPointerException if any argument is {@code null} or if any element 406 * in the {@code getters} array is {@code null} 407 * @throws Throwable if any exception is thrown during call site construction 408 */ 409 public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type, 410 Class<?> recordClass, 411 String names, 412 MethodHandle... getters) throws Throwable { 413 requireNonNull(lookup); 414 requireNonNull(methodName); 415 requireNonNull(type); 416 requireNonNull(recordClass); 417 requireNonNull(names); 418 requireNonNull(getters); 419 Arrays.stream(getters).forEach(Objects::requireNonNull); 420 MethodType methodType; 421 Class<?> receiverType = PrimitiveClass.isPrimitiveClass(recordClass) 422 ? PrimitiveClass.asValueType(recordClass) : recordClass; 423 if (type instanceof MethodType mt) { 424 methodType = mt; 425 if (mt.parameterType(0) != receiverType) { 426 throw new IllegalArgumentException("Bad method type: " + mt); 427 } 428 } else { 429 methodType = null; 430 if (!MethodHandle.class.equals(type)) 431 throw new IllegalArgumentException(type.toString()); 432 } 433 List<MethodHandle> getterList = List.of(getters); 434 for (MethodHandle getter : getterList) { 435 if (getter.type().parameterType(0) != receiverType) { 436 throw new IllegalArgumentException("Bad receiver type: " + getter); 437 } 438 } 439 MethodHandle handle = switch (methodName) { 440 case "equals" -> { 441 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, receiverType, Object.class))) 442 throw new IllegalArgumentException("Bad method type: " + methodType); 443 yield makeEquals(receiverType, getterList); 444 } 445 case "hashCode" -> { 446 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, receiverType))) 447 throw new IllegalArgumentException("Bad method type: " + methodType); 448 yield makeHashCode(receiverType, getterList); 449 } 450 case "toString" -> { 451 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, receiverType))) 452 throw new IllegalArgumentException("Bad method type: " + methodType); 453 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";")); 454 if (nameList.size() != getterList.size()) 455 throw new IllegalArgumentException("Name list and accessor list do not match"); 456 yield makeToString(lookup, receiverType, recordClass.getSimpleName(), getters, nameList); 457 } 458 default -> throw new IllegalArgumentException(methodName); 459 }; 460 return methodType != null ? new ConstantCallSite(handle) : handle; 461 } 462 }