1 /*
  2  * Copyright (c) 2017, 2021, 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                                             String simpleName,
264                                             MethodHandle[] getters,
265                                             List<String> names) {
266         assert getters.length == names.size();
267         if (getters.length == 0) {
268             // special case
269             MethodHandle emptyRecordCase = MethodHandles.constant(String.class, simpleName + "[]");
270             emptyRecordCase = MethodHandles.dropArguments(emptyRecordCase, 0, receiverClass); // (R)S
271             return emptyRecordCase;
272         }
273 
274         boolean firstTime = true;
275         MethodHandle[] mhs;
276         List<List<MethodHandle>> splits;
277         MethodHandle[] toSplit = getters;
278         int namesIndex = 0;
279         do {
280             /* StringConcatFactory::makeConcatWithConstants can only deal with 200 slots, longs and double occupy two
281              * the rest 1 slot, we need to chop the current `getters` into chunks, it could be that for records with
282              * a lot of components that we need to do a couple of iterations. The main difference between the first
283              * iteration and the rest would be on the recipe
284              */
285             splits = split(toSplit);
286             mhs = new MethodHandle[splits.size()];
287             for (int splitIndex = 0; splitIndex < splits.size(); splitIndex++) {
288                 String recipe = "";
289                 if (firstTime && splitIndex == 0) {
290                     recipe = simpleName + "[";
291                 }
292                 for (int i = 0; i < splits.get(splitIndex).size(); i++) {
293                     recipe += firstTime ? names.get(namesIndex) + "=" + "\1" : "\1";
294                     if (firstTime && namesIndex != names.size() - 1) {
295                         recipe += ", ";
296                     }
297                     namesIndex++;
298                 }
299                 if (firstTime && splitIndex == splits.size() - 1) {
300                     recipe += "]";
301                 }
302                 Class<?>[] concatTypeArgs = new Class<?>[splits.get(splitIndex).size()];
303                 // special case: no need to create another getters if there is only one split
304                 MethodHandle[] currentSplitGetters = new MethodHandle[splits.get(splitIndex).size()];
305                 for (int j = 0; j < splits.get(splitIndex).size(); j++) {
306                     concatTypeArgs[j] = splits.get(splitIndex).get(j).type().returnType();
307                     currentSplitGetters[j] = splits.get(splitIndex).get(j);
308                 }
309                 MethodType concatMT = MethodType.methodType(String.class, concatTypeArgs);
310                 try {
311                     mhs[splitIndex] = StringConcatFactory.makeConcatWithConstants(
312                             lookup, "",
313                             concatMT,
314                             recipe,
315                             new Object[0]
316                     ).getTarget();
317                     mhs[splitIndex] = MethodHandles.filterArguments(mhs[splitIndex], 0, currentSplitGetters);
318                     // this will spread the receiver class across all the getters
319                     mhs[splitIndex] = MethodHandles.permuteArguments(
320                             mhs[splitIndex],
321                             MethodType.methodType(String.class, receiverClass),
322                             new int[splits.get(splitIndex).size()]
323                     );
324                 } catch (Throwable t) {
325                     throw new RuntimeException(t);
326                 }
327             }
328             toSplit = mhs;
329             firstTime = false;
330         } while (splits.size() > 1);
331         return mhs[0];
332     }
333 
334     /**
335      * Chops the getters into smaller chunks according to the maximum number of slots
336      * StringConcatFactory::makeConcatWithConstants can chew
337      * @param getters the current getters
338      * @return chunks that wont surpass the maximum number of slots StringConcatFactory::makeConcatWithConstants can chew
339      */
340     private static List<List<MethodHandle>> split(MethodHandle[] getters) {
341         List<List<MethodHandle>> splits = new ArrayList<>();
342 
343         int slots = 0;
344 
345         // Need to peel, so that neither call has more than acceptable number
346         // of slots for the arguments.
347         List<MethodHandle> cArgs = new ArrayList<>();
348         for (MethodHandle methodHandle : getters) {
349             Class<?> returnType = methodHandle.type().returnType();
350             int needSlots = (returnType == long.class || returnType == double.class) ? 2 : 1;
351             if (slots + needSlots > MAX_STRING_CONCAT_SLOTS) {
352                 splits.add(cArgs);
353                 cArgs = new ArrayList<>();
354                 slots = 0;
355             }
356             cArgs.add(methodHandle);
357             slots += needSlots;
358         }
359 
360         // Flush the tail slice
361         if (!cArgs.isEmpty()) {
362             splits.add(cArgs);
363         }
364 
365         return splits;
366     }
367 
368     /**
369      * Bootstrap method to generate the {@link Object#equals(Object)},
370      * {@link Object#hashCode()}, and {@link Object#toString()} methods, based
371      * on a description of the component names and accessor methods, for either
372      * {@code invokedynamic} call sites or dynamic constant pool entries.
373      *
374      * For more detail on the semantics of the generated methods see the specification
375      * of {@link java.lang.Record#equals(Object)}, {@link java.lang.Record#hashCode()} and
376      * {@link java.lang.Record#toString()}.
377      *
378      *
379      * @param lookup       Every bootstrap method is expected to have a {@code lookup}
380      *                     which usually represents a lookup context with the
381      *                     accessibility privileges of the caller. This is because
382      *                     {@code invokedynamic} call sites always provide a {@code lookup}
383      *                     to the corresponding bootstrap method, but this method just
384      *                     ignores the {@code lookup} parameter
385      * @param methodName   the name of the method to generate, which must be one of
386      *                     {@code "equals"}, {@code "hashCode"}, or {@code "toString"}
387      * @param type         a {@link MethodType} corresponding the descriptor type
388      *                     for the method, which must correspond to the descriptor
389      *                     for the corresponding {@link Object} method, if linking
390      *                     an {@code invokedynamic} call site, or the
391      *                     constant {@code MethodHandle.class}, if linking a
392      *                     dynamic constant
393      * @param recordClass  the record class hosting the record components
394      * @param names        the list of component names, joined into a string
395      *                     separated by ";", or the empty string if there are no
396      *                     components. This parameter is ignored if the {@code methodName}
397      *                     parameter is {@code "equals"} or {@code "hashCode"}
398      * @param getters      method handles for the accessor methods for the components
399      * @return             a call site if invoked by indy, or a method handle
400      *                     if invoked by a condy
401      * @throws IllegalArgumentException if the bootstrap arguments are invalid
402      *                                  or inconsistent
403      * @throws NullPointerException if any argument is {@code null} or if any element
404      *                              in the {@code getters} array is {@code null}
405      * @throws Throwable if any exception is thrown during call site construction
406      */
407     public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
408                                    Class<?> recordClass,
409                                    String names,
410                                    MethodHandle... getters) throws Throwable {
411         requireNonNull(lookup);
412         requireNonNull(methodName);
413         requireNonNull(type);
414         requireNonNull(recordClass);
415         requireNonNull(names);
416         requireNonNull(getters);
417         Arrays.stream(getters).forEach(Objects::requireNonNull);
418         MethodType methodType;
419         Class<?> receiverType = recordClass.isPrimitiveClass() ? recordClass.asValueType() : recordClass;
420         if (type instanceof MethodType mt) {
421             methodType = mt;
422             if (mt.parameterType(0) != receiverType) {
423                 throw new IllegalArgumentException("Bad method type: " + mt);
424             }
425         } else {
426             methodType = null;
427             if (!MethodHandle.class.equals(type))
428                 throw new IllegalArgumentException(type.toString());
429         }
430         List<MethodHandle> getterList = List.of(getters);
431         for (MethodHandle getter : getterList) {
432             if (getter.type().parameterType(0) != receiverType) {
433                 throw new IllegalArgumentException("Bad receiver type: " + getter);
434             }
435         }
436         MethodHandle handle = switch (methodName) {
437             case "equals"   -> {
438                 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, receiverType, Object.class)))
439                     throw new IllegalArgumentException("Bad method type: " + methodType);
440                 yield makeEquals(receiverType, getterList);
441             }
442             case "hashCode" -> {
443                 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, receiverType)))
444                     throw new IllegalArgumentException("Bad method type: " + methodType);
445                 yield makeHashCode(receiverType, getterList);
446             }
447             case "toString" -> {
448                 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, receiverType)))
449                     throw new IllegalArgumentException("Bad method type: " + methodType);
450                 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
451                 if (nameList.size() != getterList.size())
452                     throw new IllegalArgumentException("Name list and accessor list do not match");
453                 yield makeToString(lookup, receiverType, recordClass.getSimpleName(), getters, nameList);
454             }
455             default -> throw new IllegalArgumentException(methodName);
456         };
457         return methodType != null ? new ConstantCallSite(handle) : handle;
458     }
459 }