1 /*
   2  * Copyright (c) 2008, 2015, 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.invoke;
  27 
  28 import java.lang.invoke.MethodHandles.Lookup;
  29 import java.lang.reflect.Field;
  30 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  31 import static java.lang.invoke.MethodHandleStatics.*;
  32 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  33 
  34 /**
  35  * The JVM interface for the method handles package is all here.
  36  * This is an interface internal and private to an implementation of JSR 292.
  37  * <em>This class is not part of the JSR 292 standard.</em>
  38  * @author jrose
  39  */
  40 class MethodHandleNatives {
  41 
  42     private MethodHandleNatives() { } // static only
  43 
  44     /// MemberName support
  45 
  46     static native void init(MemberName self, Object ref);
  47     static native void expand(MemberName self);
  48     static native MemberName resolve(MemberName self, Class<?> caller) throws LinkageError;
  49     static native int getMembers(Class<?> defc, String matchName, String matchSig,
  50             int matchFlags, Class<?> caller, int skip, MemberName[] results);
  51 
  52     /// Field layout queries parallel to sun.misc.Unsafe:
  53     static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
  54     static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
  55     static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
  56     static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
  57 
  58     /// CallSite support
  59 
  60     /** Tell the JVM that we need to change the target of a CallSite. */
  61     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
  62     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
  63 
  64     private static native void registerNatives();
  65     static {
  66         registerNatives();
  67 
  68         // The JVM calls MethodHandleNatives.<clinit>.  Cascade the <clinit> calls as needed:
  69         MethodHandleImpl.initStatics();
  70     }
  71 
  72     // All compile-time constants go here.
  73     // There is an opportunity to check them against the JVM's idea of them.
  74     static class Constants {
  75         Constants() { } // static only
  76 
  77         /**
  78          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
  79          */
  80         static final byte
  81             REF_NONE                    = 0,  // null value
  82             REF_getField                = 1,
  83             REF_getStatic               = 2,
  84             REF_putField                = 3,
  85             REF_putStatic               = 4,
  86             REF_invokeVirtual           = 5,
  87             REF_invokeStatic            = 6,
  88             REF_invokeSpecial           = 7,
  89             REF_newInvokeSpecial        = 8,
  90             REF_invokeInterface         = 9,
  91             REF_LIMIT                  = 10;
  92     }
  93 
  94     static boolean refKindIsValid(int refKind) {
  95         return (refKind > REF_NONE && refKind < REF_LIMIT);
  96     }
  97     static boolean refKindIsField(byte refKind) {
  98         assert(refKindIsValid(refKind));
  99         return (refKind <= REF_putStatic);
 100     }
 101     static boolean refKindIsGetter(byte refKind) {
 102         assert(refKindIsValid(refKind));
 103         return (refKind <= REF_getStatic);
 104     }
 105     static boolean refKindIsSetter(byte refKind) {
 106         return refKindIsField(refKind) && !refKindIsGetter(refKind);
 107     }
 108     static boolean refKindIsMethod(byte refKind) {
 109         return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
 110     }
 111     static boolean refKindIsConstructor(byte refKind) {
 112         return (refKind == REF_newInvokeSpecial);
 113     }
 114     static boolean refKindHasReceiver(byte refKind) {
 115         assert(refKindIsValid(refKind));
 116         return (refKind & 1) != 0;
 117     }
 118     static boolean refKindIsStatic(byte refKind) {
 119         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
 120     }
 121     static boolean refKindDoesDispatch(byte refKind) {
 122         assert(refKindIsValid(refKind));
 123         return (refKind == REF_invokeVirtual ||
 124                 refKind == REF_invokeInterface);
 125     }
 126     static {
 127         final int HR_MASK = ((1 << REF_getField) |
 128                              (1 << REF_putField) |
 129                              (1 << REF_invokeVirtual) |
 130                              (1 << REF_invokeSpecial) |
 131                              (1 << REF_invokeInterface)
 132                             );
 133         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
 134             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
 135         }
 136     }
 137     static String refKindName(byte refKind) {
 138         assert(refKindIsValid(refKind));
 139         switch (refKind) {
 140         case REF_getField:          return "getField";
 141         case REF_getStatic:         return "getStatic";
 142         case REF_putField:          return "putField";
 143         case REF_putStatic:         return "putStatic";
 144         case REF_invokeVirtual:     return "invokeVirtual";
 145         case REF_invokeStatic:      return "invokeStatic";
 146         case REF_invokeSpecial:     return "invokeSpecial";
 147         case REF_newInvokeSpecial:  return "newInvokeSpecial";
 148         case REF_invokeInterface:   return "invokeInterface";
 149         default:                    return "REF_???";
 150         }
 151     }
 152 
 153     private static native int getNamedCon(int which, Object[] name);
 154     static boolean verifyConstants() {
 155         Object[] box = { null };
 156         for (int i = 0; ; i++) {
 157             box[0] = null;
 158             int vmval = getNamedCon(i, box);
 159             if (box[0] == null)  break;
 160             String name = (String) box[0];
 161             try {
 162                 Field con = Constants.class.getDeclaredField(name);
 163                 int jval = con.getInt(null);
 164                 if (jval == vmval)  continue;
 165                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 166                 if (name.equals("CONV_OP_LIMIT")) {
 167                     System.err.println("warning: "+err);
 168                     continue;
 169                 }
 170                 throw new InternalError(err);
 171             } catch (NoSuchFieldException | IllegalAccessException ex) {
 172                 String err = (name+": JVM has "+vmval+" which Java does not define");
 173                 // ignore exotic ops the JVM cares about; we just wont issue them
 174                 //System.err.println("warning: "+err);
 175                 continue;
 176             }
 177         }
 178         return true;
 179     }
 180     static {
 181         assert(verifyConstants());
 182     }
 183 
 184     // Up-calls from the JVM.
 185     // These must NOT be public.
 186 
 187     /**
 188      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 189      */
 190     static MemberName linkCallSite(Object callerObj,
 191                                    Object bootstrapMethodObj,
 192                                    Object nameObj, Object typeObj,
 193                                    Object staticArguments,
 194                                    Object[] appendixResult) {
 195         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 196         Class<?> caller = (Class<?>)callerObj;
 197         String name = nameObj.toString().intern();
 198         MethodType type = (MethodType)typeObj;
 199         if (!TRACE_METHOD_LINKAGE)
 200             return linkCallSiteImpl(caller, bootstrapMethod, name, type,
 201                                     staticArguments, appendixResult);
 202         return linkCallSiteTracing(caller, bootstrapMethod, name, type,
 203                                    staticArguments, appendixResult);
 204     }
 205     static MemberName linkCallSiteImpl(Class<?> caller,
 206                                        MethodHandle bootstrapMethod,
 207                                        String name, MethodType type,
 208                                        Object staticArguments,
 209                                        Object[] appendixResult) {
 210         CallSite callSite = CallSite.makeSite(bootstrapMethod,
 211                                               name,
 212                                               type,
 213                                               staticArguments,
 214                                               caller);
 215         if (callSite instanceof ConstantCallSite) {
 216             appendixResult[0] = callSite.dynamicInvoker();
 217             return Invokers.linkToTargetMethod(type);
 218         } else {
 219             appendixResult[0] = callSite;
 220             return Invokers.linkToCallSiteMethod(type);
 221         }
 222     }
 223     // Tracing logic:
 224     static MemberName linkCallSiteTracing(Class<?> caller,
 225                                           MethodHandle bootstrapMethod,
 226                                           String name, MethodType type,
 227                                           Object staticArguments,
 228                                           Object[] appendixResult) {
 229         Object bsmReference = bootstrapMethod.internalMemberName();
 230         if (bsmReference == null)  bsmReference = bootstrapMethod;
 231         Object staticArglist = (staticArguments instanceof Object[] ?
 232                                 java.util.Arrays.asList((Object[]) staticArguments) :
 233                                 staticArguments);
 234         System.out.println("linkCallSite "+caller.getName()+" "+
 235                            bsmReference+" "+
 236                            name+type+"/"+staticArglist);
 237         try {
 238             MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type,
 239                                               staticArguments, appendixResult);
 240             System.out.println("linkCallSite => "+res+" + "+appendixResult[0]);
 241             return res;
 242         } catch (Throwable ex) {
 243             System.out.println("linkCallSite => throw "+ex);
 244             throw ex;
 245         }
 246     }
 247 
 248     /**
 249      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 250      */
 251     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 252         return MethodType.makeImpl(rtype, ptypes, true);
 253     }
 254 
 255     /**
 256      * The JVM wants to link a call site that requires a dynamic type check.
 257      * Name is a type-checking invoker, invokeExact or invoke.
 258      * Return a JVM method (MemberName) to handle the invoking.
 259      * The method assumes the following arguments on the stack:
 260      * 0: the method handle being invoked
 261      * 1-N: the arguments to the method handle invocation
 262      * N+1: an optional, implicitly added argument (typically the given MethodType)
 263      * <p>
 264      * The nominal method at such a call site is an instance of
 265      * a signature-polymorphic method (see @PolymorphicSignature).
 266      * Such method instances are user-visible entities which are
 267      * "split" from the generic placeholder method in {@code MethodHandle}.
 268      * (Note that the placeholder method is not identical with any of
 269      * its instances.  If invoked reflectively, is guaranteed to throw an
 270      * {@code UnsupportedOperationException}.)
 271      * If the signature-polymorphic method instance is ever reified,
 272      * it appears as a "copy" of the original placeholder
 273      * (a native final member of {@code MethodHandle}) except
 274      * that its type descriptor has shape required by the instance,
 275      * and the method instance is <em>not</em> varargs.
 276      * The method instance is also marked synthetic, since the
 277      * method (by definition) does not appear in Java source code.
 278      * <p>
 279      * The JVM is allowed to reify this method as instance metadata.
 280      * For example, {@code invokeBasic} is always reified.
 281      * But the JVM may instead call {@code linkMethod}.
 282      * If the result is an * ordered pair of a {@code (method, appendix)},
 283      * the method gets all the arguments (0..N inclusive)
 284      * plus the appendix (N+1), and uses the appendix to complete the call.
 285      * In this way, one reusable method (called a "linker method")
 286      * can perform the function of any number of polymorphic instance
 287      * methods.
 288      * <p>
 289      * Linker methods are allowed to be weakly typed, with any or
 290      * all references rewritten to {@code Object} and any primitives
 291      * (except {@code long}/{@code float}/{@code double})
 292      * rewritten to {@code int}.
 293      * A linker method is trusted to return a strongly typed result,
 294      * according to the specific method type descriptor of the
 295      * signature-polymorphic instance it is emulating.
 296      * This can involve (as necessary) a dynamic check using
 297      * data extracted from the appendix argument.
 298      * <p>
 299      * The JVM does not inspect the appendix, other than to pass
 300      * it verbatim to the linker method at every call.
 301      * This means that the JDK runtime has wide latitude
 302      * for choosing the shape of each linker method and its
 303      * corresponding appendix.
 304      * Linker methods should be generated from {@code LambdaForm}s
 305      * so that they do not become visible on stack traces.
 306      * <p>
 307      * The {@code linkMethod} call is free to omit the appendix
 308      * (returning null) and instead emulate the required function
 309      * completely in the linker method.
 310      * As a corner case, if N==255, no appendix is possible.
 311      * In this case, the method returned must be custom-generated to
 312      * to perform any needed type checking.
 313      * <p>
 314      * If the JVM does not reify a method at a call site, but instead
 315      * calls {@code linkMethod}, the corresponding call represented
 316      * in the bytecodes may mention a valid method which is not
 317      * representable with a {@code MemberName}.
 318      * Therefore, use cases for {@code linkMethod} tend to correspond to
 319      * special cases in reflective code such as {@code findVirtual}
 320      * or {@code revealDirect}.
 321      */
 322     static MemberName linkMethod(Class<?> callerClass, int refKind,
 323                                  Class<?> defc, String name, Object type,
 324                                  Object[] appendixResult) {
 325         if (!TRACE_METHOD_LINKAGE)
 326             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 327         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
 328     }
 329     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
 330                                      Class<?> defc, String name, Object type,
 331                                      Object[] appendixResult) {
 332         try {
 333             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
 334                 return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
 335             }
 336         } catch (Throwable ex) {
 337             if (ex instanceof LinkageError)
 338                 throw (LinkageError) ex;
 339             else
 340                 throw new LinkageError(ex.getMessage(), ex);
 341         }
 342         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
 343     }
 344     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
 345         if (type instanceof MethodType)
 346             return (MethodType) type;
 347         else
 348             return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
 349     }
 350     // Tracing logic:
 351     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
 352                                         Class<?> defc, String name, Object type,
 353                                         Object[] appendixResult) {
 354         System.out.println("linkMethod "+defc.getName()+"."+
 355                            name+type+"/"+Integer.toHexString(refKind));
 356         try {
 357             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 358             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
 359             return res;
 360         } catch (Throwable ex) {
 361             System.out.println("linkMethod => throw "+ex);
 362             throw ex;
 363         }
 364     }
 365 
 366 
 367     /**
 368      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 369      * It will make an up-call to this method.  (Do not change the name or signature.)
 370      * The type argument is a Class for field requests and a MethodType for non-fields.
 371      * <p>
 372      * Recent versions of the JVM may also pass a resolved MemberName for the type.
 373      * In that case, the name is ignored and may be null.
 374      */
 375     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 376                                                  Class<?> defc, String name, Object type) {
 377         try {
 378             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 379             assert(refKindIsValid(refKind));
 380             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
 381         } catch (IllegalAccessException ex) {
 382             Throwable cause = ex.getCause();
 383             if (cause instanceof AbstractMethodError) {
 384                 throw (AbstractMethodError) cause;
 385             } else {
 386                 Error err = new IllegalAccessError(ex.getMessage());
 387                 throw initCauseFrom(err, ex);
 388             }
 389         } catch (NoSuchMethodException ex) {
 390             Error err = new NoSuchMethodError(ex.getMessage());
 391             throw initCauseFrom(err, ex);
 392         } catch (NoSuchFieldException ex) {
 393             Error err = new NoSuchFieldError(ex.getMessage());
 394             throw initCauseFrom(err, ex);
 395         } catch (ReflectiveOperationException ex) {
 396             Error err = new IncompatibleClassChangeError();
 397             throw initCauseFrom(err, ex);
 398         }
 399     }
 400 
 401     /**
 402      * Use best possible cause for err.initCause(), substituting the
 403      * cause for err itself if the cause has the same (or better) type.
 404      */
 405     static private Error initCauseFrom(Error err, Exception ex) {
 406         Throwable th = ex.getCause();
 407         if (err.getClass().isInstance(th))
 408            return (Error) th;
 409         err.initCause(th == null ? ex : th);
 410         return err;
 411     }
 412 
 413     /**
 414      * Is this method a caller-sensitive method?
 415      * I.e., does it call Reflection.getCallerClass or a similar method
 416      * to ask about the identity of its caller?
 417      */
 418     static boolean isCallerSensitive(MemberName mem) {
 419         if (!mem.isInvocable())  return false;  // fields are not caller sensitive
 420 
 421         return mem.isCallerSensitive() || canBeCalledVirtual(mem);
 422     }
 423 
 424     static boolean canBeCalledVirtual(MemberName mem) {
 425         assert(mem.isInvocable());
 426         Class<?> defc = mem.getDeclaringClass();
 427         switch (mem.getName()) {
 428         case "checkMemberAccess":
 429             return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
 430         case "getContextClassLoader":
 431             return canBeCalledVirtual(mem, java.lang.Thread.class);
 432         }
 433         return false;
 434     }
 435 
 436     static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
 437         Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
 438         if (symbolicRefClass == definingClass)  return true;
 439         if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
 440         return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
 441                 symbolicRefClass.isInterface());                     // Mdef implements Msym
 442     }
 443 }