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