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