1 /*
2  * Copyright (c) 2017, 2020, 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.TypeDescriptor;
33 import java.security.AccessController;
34 import java.security.PrivilegedAction;
35 import java.util.Arrays;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Objects;
39 
40 /**
41  * Bootstrap methods for state-driven implementations of core methods,
42  * including {@link Object#equals(Object)}, {@link Object#hashCode()}, and
43  * {@link Object#toString()}.  These methods may be used, for example, by
44  * Java compiler implementations to implement the bodies of {@link Object}
45  * methods for record classes.
46  *
47  * @since 16
48  */
49 public class ObjectMethods {
50 
ObjectMethods()51     private ObjectMethods() { }
52 
53     private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class);
54     private static final MethodType NAMES_MT = MethodType.methodType(List.class);
55     private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false);
56     private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true);
57     private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0);
58     private static final MethodHandle CLASS_IS_INSTANCE;
59     private static final MethodHandle OBJECT_EQUALS;
60     private static final MethodHandle OBJECTS_EQUALS;
61     private static final MethodHandle OBJECTS_HASHCODE;
62     private static final MethodHandle OBJECTS_TOSTRING;
63     private static final MethodHandle OBJECT_EQ;
64     private static final MethodHandle OBJECT_HASHCODE;
65     private static final MethodHandle OBJECT_TO_STRING;
66     private static final MethodHandle STRING_FORMAT;
67     private static final MethodHandle HASH_COMBINER;
68 
69     private static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>();
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             ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
80                 @Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); }
81             });
82 
83             CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance",
84                                                          MethodType.methodType(boolean.class, Object.class));
85             OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals",
86                                                      MethodType.methodType(boolean.class, Object.class));
87             OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode",
88                                                        MethodType.fromMethodDescriptorString("()I", loader));
89             OBJECT_TO_STRING = publicLookup.findVirtual(Object.class, "toString",
90                                                         MethodType.methodType(String.class));
91             STRING_FORMAT = publicLookup.findStatic(String.class, "format",
92                                                     MethodType.methodType(String.class, String.class, Object[].class));
93             OBJECTS_EQUALS = publicLookup.findStatic(Objects.class, "equals",
94                                                      MethodType.methodType(boolean.class, Object.class, Object.class));
95             OBJECTS_HASHCODE = publicLookup.findStatic(Objects.class, "hashCode",
96                                                        MethodType.methodType(int.class, Object.class));
97             OBJECTS_TOSTRING = publicLookup.findStatic(Objects.class, "toString",
98                                                        MethodType.methodType(String.class, Object.class));
99 
100             OBJECT_EQ = lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
101                                           MethodType.methodType(boolean.class, Object.class, Object.class));
102             HASH_COMBINER = lookup.findStatic(OBJECT_METHODS_CLASS, "hashCombiner",
103                                               MethodType.fromMethodDescriptorString("(II)I", loader));
104 
primitiveEquals.put(byte.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))105             primitiveEquals.put(byte.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
106                                                               MethodType.fromMethodDescriptorString("(BB)Z", loader)));
primitiveEquals.put(short.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))107             primitiveEquals.put(short.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
108                                                                MethodType.fromMethodDescriptorString("(SS)Z", loader)));
primitiveEquals.put(char.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))109             primitiveEquals.put(char.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
110                                                               MethodType.fromMethodDescriptorString("(CC)Z", loader)));
primitiveEquals.put(int.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))111             primitiveEquals.put(int.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
112                                                              MethodType.fromMethodDescriptorString("(II)Z", loader)));
primitiveEquals.put(long.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))113             primitiveEquals.put(long.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
114                                                               MethodType.fromMethodDescriptorString("(JJ)Z", loader)));
primitiveEquals.put(float.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))115             primitiveEquals.put(float.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
116                                                                MethodType.fromMethodDescriptorString("(FF)Z", loader)));
primitiveEquals.put(double.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))117             primitiveEquals.put(double.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
118                                                                 MethodType.fromMethodDescriptorString("(DD)Z", loader)));
primitiveEquals.put(boolean.class, lookup.findStatic(OBJECT_METHODS_CLASS, R, MethodType.fromMethodDescriptorString(R, loader)))119             primitiveEquals.put(boolean.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
120                                                                  MethodType.fromMethodDescriptorString("(ZZ)Z", loader)));
121 
primitiveHashers.put(byte.class, lookup.findStatic(Byte.class, R, MethodType.fromMethodDescriptorString(R, loader)))122             primitiveHashers.put(byte.class, lookup.findStatic(Byte.class, "hashCode",
123                                                                MethodType.fromMethodDescriptorString("(B)I", loader)));
primitiveHashers.put(short.class, lookup.findStatic(Short.class, R, MethodType.fromMethodDescriptorString(R, loader)))124             primitiveHashers.put(short.class, lookup.findStatic(Short.class, "hashCode",
125                                                                 MethodType.fromMethodDescriptorString("(S)I", loader)));
primitiveHashers.put(char.class, lookup.findStatic(Character.class, R, MethodType.fromMethodDescriptorString(R, loader)))126             primitiveHashers.put(char.class, lookup.findStatic(Character.class, "hashCode",
127                                                                MethodType.fromMethodDescriptorString("(C)I", loader)));
primitiveHashers.put(int.class, lookup.findStatic(Integer.class, R, MethodType.fromMethodDescriptorString(R, loader)))128             primitiveHashers.put(int.class, lookup.findStatic(Integer.class, "hashCode",
129                                                               MethodType.fromMethodDescriptorString("(I)I", loader)));
primitiveHashers.put(long.class, lookup.findStatic(Long.class, R, MethodType.fromMethodDescriptorString(R, loader)))130             primitiveHashers.put(long.class, lookup.findStatic(Long.class, "hashCode",
131                                                                MethodType.fromMethodDescriptorString("(J)I", loader)));
primitiveHashers.put(float.class, lookup.findStatic(Float.class, R, MethodType.fromMethodDescriptorString(R, loader)))132             primitiveHashers.put(float.class, lookup.findStatic(Float.class, "hashCode",
133                                                                 MethodType.fromMethodDescriptorString("(F)I", loader)));
primitiveHashers.put(double.class, lookup.findStatic(Double.class, R, MethodType.fromMethodDescriptorString(R, loader)))134             primitiveHashers.put(double.class, lookup.findStatic(Double.class, "hashCode",
135                                                                  MethodType.fromMethodDescriptorString("(D)I", loader)));
primitiveHashers.put(boolean.class, lookup.findStatic(Boolean.class, R, MethodType.fromMethodDescriptorString(R, loader)))136             primitiveHashers.put(boolean.class, lookup.findStatic(Boolean.class, "hashCode",
137                                                                   MethodType.fromMethodDescriptorString("(Z)I", loader)));
138 
primitiveToString.put(byte.class, lookup.findStatic(Byte.class, R, MethodType.methodType(String.class, byte.class)))139             primitiveToString.put(byte.class, lookup.findStatic(Byte.class, "toString",
140                                                                 MethodType.methodType(String.class, byte.class)));
primitiveToString.put(short.class, lookup.findStatic(Short.class, R, MethodType.methodType(String.class, short.class)))141             primitiveToString.put(short.class, lookup.findStatic(Short.class, "toString",
142                                                                  MethodType.methodType(String.class, short.class)));
primitiveToString.put(char.class, lookup.findStatic(Character.class, R, MethodType.methodType(String.class, char.class)))143             primitiveToString.put(char.class, lookup.findStatic(Character.class, "toString",
144                                                                 MethodType.methodType(String.class, char.class)));
primitiveToString.put(int.class, lookup.findStatic(Integer.class, R, MethodType.methodType(String.class, int.class)))145             primitiveToString.put(int.class, lookup.findStatic(Integer.class, "toString",
146                                                                MethodType.methodType(String.class, int.class)));
primitiveToString.put(long.class, lookup.findStatic(Long.class, R, MethodType.methodType(String.class, long.class)))147             primitiveToString.put(long.class, lookup.findStatic(Long.class, "toString",
148                                                                 MethodType.methodType(String.class, long.class)));
primitiveToString.put(float.class, lookup.findStatic(Float.class, R, MethodType.methodType(String.class, float.class)))149             primitiveToString.put(float.class, lookup.findStatic(Float.class, "toString",
150                                                                  MethodType.methodType(String.class, float.class)));
primitiveToString.put(double.class, lookup.findStatic(Double.class, R, MethodType.methodType(String.class, double.class)))151             primitiveToString.put(double.class, lookup.findStatic(Double.class, "toString",
152                                                                   MethodType.methodType(String.class, double.class)));
primitiveToString.put(boolean.class, lookup.findStatic(Boolean.class, R, MethodType.methodType(String.class, boolean.class)))153             primitiveToString.put(boolean.class, lookup.findStatic(Boolean.class, "toString",
154                                                                    MethodType.methodType(String.class, boolean.class)));
155         }
156         catch (ReflectiveOperationException e) {
157             throw new RuntimeException(e);
158         }
159     }
160 
hashCombiner(int x, int y)161     private static int hashCombiner(int x, int y) {
162         return x*31 + y;
163     }
164 
eq(Object a, Object b)165     private static boolean eq(Object a, Object b) { return a == b; }
eq(byte a, byte b)166     private static boolean eq(byte a, byte b) { return a == b; }
eq(short a, short b)167     private static boolean eq(short a, short b) { return a == b; }
eq(char a, char b)168     private static boolean eq(char a, char b) { return a == b; }
eq(int a, int b)169     private static boolean eq(int a, int b) { return a == b; }
eq(long a, long b)170     private static boolean eq(long a, long b) { return a == b; }
eq(float a, float b)171     private static boolean eq(float a, float b) { return Float.compare(a, b) == 0; }
eq(double a, double b)172     private static boolean eq(double a, double b) { return Double.compare(a, b) == 0; }
eq(boolean a, boolean b)173     private static boolean eq(boolean a, boolean b) { return a == b; }
174 
175     /** Get the method handle for combining two values of a given type */
equalator(Class<?> clazz)176     private static MethodHandle equalator(Class<?> clazz) {
177         return (clazz.isPrimitive()
178                 ? primitiveEquals.get(clazz)
179                 : OBJECTS_EQUALS.asType(MethodType.methodType(boolean.class, clazz, clazz)));
180     }
181 
182     /** Get the hasher for a value of a given type */
hasher(Class<?> clazz)183     private static MethodHandle hasher(Class<?> clazz) {
184         return (clazz.isPrimitive()
185                 ? primitiveHashers.get(clazz)
186                 : OBJECTS_HASHCODE.asType(MethodType.methodType(int.class, clazz)));
187     }
188 
189     /** Get the stringifier for a value of a given type */
stringifier(Class<?> clazz)190     private static MethodHandle stringifier(Class<?> clazz) {
191         return (clazz.isPrimitive()
192                 ? primitiveToString.get(clazz)
193                 : OBJECTS_TOSTRING.asType(MethodType.methodType(String.class, clazz)));
194     }
195 
196     /**
197      * Generates a method handle for the {@code equals} method for a given data class
198      * @param receiverClass   the data class
199      * @param getters         the list of getters
200      * @return the method handle
201      */
makeEquals(Class<?> receiverClass, List<MethodHandle> getters)202     private static MethodHandle makeEquals(Class<?> receiverClass,
203                                           List<MethodHandle> getters) {
204         MethodType rr = MethodType.methodType(boolean.class, receiverClass, receiverClass);
205         MethodType ro = MethodType.methodType(boolean.class, receiverClass, Object.class);
206         MethodHandle instanceFalse = MethodHandles.dropArguments(FALSE, 0, receiverClass, Object.class); // (RO)Z
207         MethodHandle instanceTrue = MethodHandles.dropArguments(TRUE, 0, receiverClass, Object.class); // (RO)Z
208         MethodHandle isSameObject = OBJECT_EQ.asType(ro); // (RO)Z
209         MethodHandle isInstance = MethodHandles.dropArguments(CLASS_IS_INSTANCE.bindTo(receiverClass), 0, receiverClass); // (RO)Z
210         MethodHandle accumulator = MethodHandles.dropArguments(TRUE, 0, receiverClass, receiverClass); // (RR)Z
211 
212         for (MethodHandle getter : getters) {
213             MethodHandle equalator = equalator(getter.type().returnType()); // (TT)Z
214             MethodHandle thisFieldEqual = MethodHandles.filterArguments(equalator, 0, getter, getter); // (RR)Z
215             accumulator = MethodHandles.guardWithTest(thisFieldEqual, accumulator, instanceFalse.asType(rr));
216         }
217 
218         return MethodHandles.guardWithTest(isSameObject,
219                                            instanceTrue,
220                                            MethodHandles.guardWithTest(isInstance, accumulator.asType(ro), instanceFalse));
221     }
222 
223     /**
224      * Generates a method handle for the {@code hashCode} method for a given data class
225      * @param receiverClass   the data class
226      * @param getters         the list of getters
227      * @return the method handle
228      */
makeHashCode(Class<?> receiverClass, List<MethodHandle> getters)229     private static MethodHandle makeHashCode(Class<?> receiverClass,
230                                             List<MethodHandle> getters) {
231         MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I
232 
233         // @@@ Use loop combinator instead?
234         for (MethodHandle getter : getters) {
235             MethodHandle hasher = hasher(getter.type().returnType()); // (T)I
236             MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter);    // (R)I
237             MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I
238             accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I
239         }
240 
241         return accumulator;
242     }
243 
244     /**
245      * Generates a method handle for the {@code toString} method for a given data class
246      * @param receiverClass   the data class
247      * @param getters         the list of getters
248      * @param names           the names
249      * @return the method handle
250      */
makeToString(Class<?> receiverClass, List<MethodHandle> getters, List<String> names)251     private static MethodHandle makeToString(Class<?> receiverClass,
252                                             List<MethodHandle> getters,
253                                             List<String> names) {
254         // This is a pretty lousy algorithm; we spread the receiver over N places,
255         // apply the N getters, apply N toString operations, and concat the result with String.format
256         // Better to use String.format directly, or delegate to StringConcatFactory
257         // Also probably want some quoting around String components
258 
259         assert getters.size() == names.size();
260 
261         int[] invArgs = new int[getters.size()];
262         Arrays.fill(invArgs, 0);
263         MethodHandle[] filters = new MethodHandle[getters.size()];
264         StringBuilder sb = new StringBuilder();
265         sb.append(receiverClass.getSimpleName()).append("[");
266         for (int i=0; i<getters.size(); i++) {
267             MethodHandle getter = getters.get(i); // (R)T
268             MethodHandle stringify = stringifier(getter.type().returnType()); // (T)String
269             MethodHandle stringifyThisField = MethodHandles.filterArguments(stringify, 0, getter);    // (R)String
270             filters[i] = stringifyThisField;
271             sb.append(names.get(i)).append("=%s");
272             if (i != getters.size() - 1)
273                 sb.append(", ");
274         }
275         sb.append(']');
276         String formatString = sb.toString();
277         MethodHandle formatter = MethodHandles.insertArguments(STRING_FORMAT, 0, formatString)
278                                               .asCollector(String[].class, getters.size()); // (R*)String
279         if (getters.size() == 0) {
280             // Add back extra R
281             formatter = MethodHandles.dropArguments(formatter, 0, receiverClass);
282         }
283         else {
284             MethodHandle filtered = MethodHandles.filterArguments(formatter, 0, filters);
285             formatter = MethodHandles.permuteArguments(filtered, MethodType.methodType(String.class, receiverClass), invArgs);
286         }
287 
288         return formatter;
289     }
290 
291     /**
292      * Bootstrap method to generate the {@link Object#equals(Object)},
293      * {@link Object#hashCode()}, and {@link Object#toString()} methods, based
294      * on a description of the component names and accessor methods, for either
295      * {@code invokedynamic} call sites or dynamic constant pool entries.
296      *
297      * For more detail on the semantics of the generated methods see the specification
298      * of {@link java.lang.Record#equals(Object)}, {@link java.lang.Record#hashCode()} and
299      * {@link java.lang.Record#toString()}.
300      *
301      *
302      * @param lookup       Every bootstrap method is expected to have a {@code lookup}
303      *                     which usually represents a lookup context with the
304      *                     accessibility privileges of the caller. This is because
305      *                     {@code invokedynamic} call sites always provide a {@code lookup}
306      *                     to the corresponding bootstrap method, but this method just
307      *                     ignores the {@code lookup} parameter
308      * @param methodName   the name of the method to generate, which must be one of
309      *                     {@code "equals"}, {@code "hashCode"}, or {@code "toString"}
310      * @param type         a {@link MethodType} corresponding the descriptor type
311      *                     for the method, which must correspond to the descriptor
312      *                     for the corresponding {@link Object} method, if linking
313      *                     an {@code invokedynamic} call site, or the
314      *                     constant {@code MethodHandle.class}, if linking a
315      *                     dynamic constant
316      * @param recordClass  the record class hosting the record components
317      * @param names        the list of component names, joined into a string
318      *                     separated by ";", or the empty string if there are no
319      *                     components. Maybe be null, if the {@code methodName}
320      *                     is {@code "equals"} or {@code "hashCode"}.
321      * @param getters      method handles for the accessor methods for the components
322      * @return             a call site if invoked by indy, or a method handle
323      *                     if invoked by a condy
324      * @throws IllegalArgumentException if the bootstrap arguments are invalid
325      *                                  or inconsistent
326      * @throws Throwable if any exception is thrown during call site construction
327      */
bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type, Class<?> recordClass, String names, MethodHandle... getters)328     public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
329                                    Class<?> recordClass,
330                                    String names,
331                                    MethodHandle... getters) throws Throwable {
332         MethodType methodType;
333         if (type instanceof MethodType)
334             methodType = (MethodType) type;
335         else {
336             methodType = null;
337             if (!MethodHandle.class.equals(type))
338                 throw new IllegalArgumentException(type.toString());
339         }
340         List<MethodHandle> getterList = List.of(getters);
341         MethodHandle handle;
342         switch (methodName) {
343             case "equals":
344                 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, recordClass, Object.class)))
345                     throw new IllegalArgumentException("Bad method type: " + methodType);
346                 handle = makeEquals(recordClass, getterList);
347                 return methodType != null ? new ConstantCallSite(handle) : handle;
348             case "hashCode":
349                 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, recordClass)))
350                     throw new IllegalArgumentException("Bad method type: " + methodType);
351                 handle = makeHashCode(recordClass, getterList);
352                 return methodType != null ? new ConstantCallSite(handle) : handle;
353             case "toString":
354                 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, recordClass)))
355                     throw new IllegalArgumentException("Bad method type: " + methodType);
356                 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
357                 if (nameList.size() != getterList.size())
358                     throw new IllegalArgumentException("Name list and accessor list do not match");
359                 handle = makeToString(recordClass, getterList, nameList);
360                 return methodType != null ? new ConstantCallSite(handle) : handle;
361             default:
362                 throw new IllegalArgumentException(methodName);
363         }
364     }
365 }
366