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