1 /*
   2  * Copyright (c) 2017, 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 package java.lang.invoke;
  26 
  27 import sun.invoke.util.Wrapper;
  28 
  29 import static java.lang.invoke.MethodHandleNatives.mapLookupExceptionToError;
  30 import static java.util.Objects.requireNonNull;
  31 
  32 /**
  33  * Bootstrap methods for dynamically-computed constants.
  34  *
  35  * <p>The bootstrap methods in this class will throw a
  36  * {@code NullPointerException} for any reference argument that is {@code null},
  37  * unless the argument is specified to be unused or specified to accept a
  38  * {@code null} value.
  39  *
  40  * @since 10
  41  */
  42 public final class ConstantBootstraps {
  43     // implements the upcall from the JVM, MethodHandleNatives.linkDynamicConstant:
  44     /*non-public*/
  45     static Object makeConstant(MethodHandle bootstrapMethod,
  46                                // Callee information:
  47                                String name, Class<?> type,
  48                                // Extra arguments for BSM, if any:
  49                                Object info,
  50                                // Caller information:
  51                                Class<?> callerClass) {
  52         // BSMI.invoke handles all type checking and exception translation.
  53         // If type is not a reference type, the JVM is expecting a boxed
  54         // version, and will manage unboxing on the other side.
  55         return BootstrapMethodInvoker.invoke(
  56                 type, bootstrapMethod, name, type, info, callerClass);
  57     }
  58 
  59     /**
  60      * Returns a {@code null} object reference for the reference type specified
  61      * by {@code type}.
  62      *
  63      * @param lookup unused
  64      * @param name unused
  65      * @param type a reference type
  66      * @return a {@code null} value
  67      * @throws IllegalArgumentException if {@code type} is not a reference type
  68      */
  69     public static Object nullConstant(MethodHandles.Lookup lookup, String name, Class<?> type) {
  70         if (requireNonNull(type).isPrimitive()) {
  71             throw new IllegalArgumentException(String.format("not reference: %s", type));
  72         }
  73 
  74         return null;
  75     }
  76 
  77     /**
  78      * Returns a {@link Class} mirror for the primitive type whose type
  79      * descriptor is specified by {@code name}.
  80      *
  81      * @param lookup unused
  82      * @param name the descriptor (JVMS 4.3) of the desired primitive type
  83      * @param type the required result type (must be {@code Class.class})
  84      * @return the {@link Class} mirror
  85      * @throws IllegalArgumentException if the name is not a descriptor for a
  86      * primitive type or the type is not {@code Class.class}
  87      */
  88     public static Class<?> primitiveClass(MethodHandles.Lookup lookup, String name, Class<?> type) {
  89         requireNonNull(name);
  90         requireNonNull(type);
  91         if (type != Class.class) {
  92             throw new IllegalArgumentException();
  93         }
  94         if (name.length() == 0 || name.length() > 1) {
  95             throw new IllegalArgumentException(String.format("not primitive: %s", name));
  96         }
  97 
  98         return Wrapper.forPrimitiveType(name.charAt(0)).primitiveType();
  99     }
 100 
 101     /**
 102      * Returns an {@code enum} constant of the type specified by {@code type}
 103      * with the name specified by {@code name}.
 104      *
 105      * @param lookup the lookup context describing the class performing the
 106      * operation (normally stacked by the JVM)
 107      * @param type the {@code Class} object describing the enum type for which
 108      * a constant is to be returned
 109      * @param name the name of the constant to return, which must exactly match
 110      * an enum constant in the specified type.
 111      * @param <E> The enum type for which a constant value is to be returned
 112      * @return the enum constant of the specified enum type with the
 113      * specified name
 114      * @throws IllegalAccessError if the declaring class or the field is not
 115      * accessible to the class performing the operation
 116      * @throws IllegalArgumentException if the specified enum type has
 117      * no constant with the specified name, or the specified
 118      * class object does not represent an enum type
 119      * @see Enum#valueOf(Class, String)
 120      */
 121     public static <E extends Enum<E>> E enumConstant(MethodHandles.Lookup lookup, String name, Class<E> type) {
 122         requireNonNull(lookup);
 123         requireNonNull(name);
 124         requireNonNull(type);
 125         validateClassAccess(lookup, type);
 126 
 127         return Enum.valueOf(type, name);
 128     }
 129 
 130     /**
 131      * Returns the value of a static final field.
 132      *
 133      * @param lookup the lookup context describing the class performing the
 134      * operation (normally stacked by the JVM)
 135      * @param name the name of the field
 136      * @param type the type of the field
 137      * @param declaringClass the class in which the field is declared
 138      * @return the value of the field
 139      * @throws IllegalAccessError if the declaring class or the field is not
 140      * accessible to the class performing the operation
 141      * @throws NoSuchFieldError if the specified field does not exist
 142      * @throws IncompatibleClassChangeError if the specified field is not
 143      * {@code final}
 144      */
 145     public static Object getStaticFinal(MethodHandles.Lookup lookup, String name, Class<?> type,
 146                                         Class<?> declaringClass) {
 147         requireNonNull(lookup);
 148         requireNonNull(name);
 149         requireNonNull(type);
 150         requireNonNull(declaringClass);
 151 
 152         MethodHandle mh;
 153         try {
 154             mh = lookup.findStaticGetter(declaringClass, name, type);
 155             MemberName member = mh.internalMemberName();
 156             if (!member.isFinal()) {
 157                 throw new IncompatibleClassChangeError("not a final field: " + name);
 158             }
 159         }
 160         catch (ReflectiveOperationException ex) {
 161             throw mapLookupExceptionToError(ex);
 162         }
 163 
 164         // Since mh is a handle to a static field only instances of
 165         // VirtualMachineError are anticipated to be thrown, such as a
 166         // StackOverflowError or an InternalError from the j.l.invoke code
 167         try {
 168             return mh.invoke();
 169         }
 170         catch (RuntimeException | Error e) {
 171             throw e;
 172         }
 173         catch (Throwable e) {
 174             throw new LinkageError("Unexpected throwable", e);
 175         }
 176     }
 177 
 178     /**
 179      * Returns the value of a static final field declared in the class which
 180      * is the same as the field's type (or, for primitive-valued fields,
 181      * declared in the wrapper class.)  This is a simplified form of
 182      * {@link #getStaticFinal(MethodHandles.Lookup, String, Class, Class)}
 183      * for the case where a class declares distinguished constant instances of
 184      * itself.
 185      *
 186      * @param lookup the lookup context describing the class performing the
 187      * operation (normally stacked by the JVM)
 188      * @param name the name of the field
 189      * @param type the type of the field
 190      * @return the value of the field
 191      * @throws IllegalAccessError if the declaring class or the field is not
 192      * accessible to the class performing the operation
 193      * @throws NoSuchFieldError if the specified field does not exist
 194      * @throws IncompatibleClassChangeError if the specified field is not
 195      * {@code final}
 196      * @see #getStaticFinal(MethodHandles.Lookup, String, Class, Class)
 197      */
 198     public static Object getStaticFinal(MethodHandles.Lookup lookup, String name, Class<?> type) {
 199         requireNonNull(type);
 200 
 201         Class<?> declaring = type.isPrimitive()
 202                              ? Wrapper.forPrimitiveType(type).wrapperType()
 203                              : type;
 204         return getStaticFinal(lookup, name, type, declaring);
 205     }
 206 
 207 
 208     /**
 209      * Returns the result of invoking a method handle with the provided
 210      * arguments.
 211      *
 212      * @param lookup the lookup context describing the class performing the
 213      * operation (normally stacked by the JVM)
 214      * @param name unused
 215      * @param type the type of the value to be returned, which must be
 216      * compatible with the return type of the method handle
 217      * @param handle the method handle to be invoked
 218      * @param args the arguments to pass to the method handle, as if with
 219      * {@link MethodHandle#invokeWithArguments}.  Each argument may be
 220      * {@code null}.
 221      * @return the result of invoking the method handle
 222      * @throws WrongMethodTypeException if the handle's return type cannot be
 223      * adjusted to the desired type
 224      * @throws ClassCastException if an argument cannot be converted by
 225      * reference casting
 226      * @throws Throwable anything thrown by the method handle invocation
 227      */
 228     public static Object invoke(MethodHandles.Lookup lookup, String name, Class<?> type,
 229                                 MethodHandle handle, Object... args) throws Throwable {
 230         requireNonNull(type);
 231         requireNonNull(handle);
 232         requireNonNull(args);
 233 
 234         if (type != handle.type().returnType()) {
 235             handle = handle.asType(handle.type().changeReturnType(type));
 236         }
 237 
 238         return handle.invokeWithArguments(args);
 239     }
 240 
 241     /**
 242      * Finds a {@link VarHandle} for an instance field.
 243      *
 244      * @param lookup the lookup context describing the class performing the
 245      * operation (normally stacked by the JVM)
 246      * @param name the name of the field
 247      * @param type the required result type (must be {@code Class<VarHandle>})
 248      * @param declaringClass the class in which the field is declared
 249      * @param fieldType the type of the field
 250      * @return the {@link VarHandle}
 251      * @throws IllegalAccessError if the declaring class or the field is not
 252      * accessible to the class performing the operation
 253      * @throws NoSuchFieldError if the specified field does not exist
 254      * @throws IllegalArgumentException if the type is not {@code VarHandle}
 255      */
 256     public static VarHandle fieldVarHandle(MethodHandles.Lookup lookup, String name, Class<VarHandle> type,
 257                                            Class<?> declaringClass, Class<?> fieldType) {
 258         requireNonNull(lookup);
 259         requireNonNull(name);
 260         requireNonNull(type);
 261         requireNonNull(declaringClass);
 262         requireNonNull(fieldType);
 263         if (type != VarHandle.class) {
 264             throw new IllegalArgumentException();
 265         }
 266 
 267         try {
 268             return lookup.findVarHandle(declaringClass, name, fieldType);
 269         }
 270         catch (ReflectiveOperationException e) {
 271             throw mapLookupExceptionToError(e);
 272         }
 273     }
 274 
 275     /**
 276      * Finds a {@link VarHandle} for a static field.
 277      *
 278      * @param lookup the lookup context describing the class performing the
 279      * operation (normally stacked by the JVM)
 280      * @param name the name of the field
 281      * @param type the required result type (must be {@code Class<VarHandle>})
 282      * @param declaringClass the class in which the field is declared
 283      * @param fieldType the type of the field
 284      * @return the {@link VarHandle}
 285      * @throws IllegalAccessError if the declaring class or the field is not
 286      * accessible to the class performing the operation
 287      * @throws NoSuchFieldError if the specified field does not exist
 288      * @throws IllegalArgumentException if the type is not {@code VarHandle}
 289      */
 290     public static VarHandle staticFieldVarHandle(MethodHandles.Lookup lookup, String name, Class<VarHandle> type,
 291                                                  Class<?> declaringClass, Class<?> fieldType) {
 292         requireNonNull(lookup);
 293         requireNonNull(name);
 294         requireNonNull(type);
 295         requireNonNull(declaringClass);
 296         requireNonNull(fieldType);
 297         if (type != VarHandle.class) {
 298             throw new IllegalArgumentException();
 299         }
 300 
 301         try {
 302             return lookup.findStaticVarHandle(declaringClass, name, fieldType);
 303         }
 304         catch (ReflectiveOperationException e) {
 305             throw mapLookupExceptionToError(e);
 306         }
 307     }
 308 
 309     /**
 310      * Finds a {@link VarHandle} for an array type.
 311      *
 312      * @param lookup the lookup context describing the class performing the
 313      * operation (normally stacked by the JVM)
 314      * @param name unused
 315      * @param type the required result type (must be {@code Class<VarHandle>})
 316      * @param arrayClass the type of the array
 317      * @return the {@link VarHandle}
 318      * @throws IllegalAccessError if the component type of the array is not
 319      * accessible to the class performing the operation
 320      * @throws IllegalArgumentException if the type is not {@code VarHandle}
 321      */
 322     public static VarHandle arrayVarHandle(MethodHandles.Lookup lookup, String name, Class<VarHandle> type,
 323                                            Class<?> arrayClass) {
 324         requireNonNull(lookup);
 325         requireNonNull(type);
 326         requireNonNull(arrayClass);
 327         if (type != VarHandle.class) {
 328             throw new IllegalArgumentException();
 329         }
 330 
 331         return MethodHandles.arrayElementVarHandle(validateClassAccess(lookup, arrayClass));
 332     }
 333 
 334     private static <T> Class<T> validateClassAccess(MethodHandles.Lookup lookup, Class<T> type) {
 335         try {
 336             lookup.accessClass(type);
 337             return type;
 338         }
 339         catch (ReflectiveOperationException ex) {
 340             throw mapLookupExceptionToError(ex);
 341         }
 342     }
 343 }