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