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