rt/emul/compact/src/main/java/java/lang/invoke/MethodHandleNatives.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 12 Aug 2014 22:57:16 +0200
branchjdk8
changeset 1671 c1732e50ebe7
parent 1670 b913b6b415a0
permissions -rw-r--r--
Need to initialize flags. getFields throws SecurityException on bck2brwsr VM - avoid.
     1 /*
     2  * Copyright (c) 2008, 2013, 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 static java.lang.invoke.MethodHandleNatives.Constants.*;
    29 import static java.lang.invoke.MethodHandleStatics.*;
    30 import java.lang.invoke.MethodHandles.Lookup;
    31 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
    32 import java.lang.reflect.Constructor;
    33 import java.lang.reflect.Field;
    34 import java.lang.reflect.Member;
    35 import java.lang.reflect.Method;
    36 
    37 /**
    38  * The JVM interface for the method handles package is all here.
    39  * This is an interface internal and private to an implementation of JSR 292.
    40  * <em>This class is not part of the JSR 292 standard.</em>
    41  * @author jrose
    42  */
    43 class MethodHandleNatives {
    44 
    45     private MethodHandleNatives() { } // static only
    46 
    47     /// MemberName support
    48 
    49     static void init(MemberName self, Object ref) {
    50         final Member mem = (Member)ref;
    51         self.clazz = mem.getDeclaringClass();
    52         int mod = mem.getModifiers();
    53         if (ref instanceof Method) {
    54             mod  |= MemberName.IS_METHOD;
    55         }
    56         if (ref instanceof Constructor) {
    57             mod  |= MemberName.IS_CONSTRUCTOR;
    58         }
    59         self.flags = mod;
    60     }
    61     
    62     static void expand(MemberName self) {
    63     }
    64     
    65     static MemberName resolve(MemberName self, Class<?> caller) throws LinkageError {
    66         return self;
    67     }
    68     static int getMembers(Class<?> defc, String matchName, String matchSig,
    69             int matchFlags, Class<?> caller, int skip, MemberName[] results) {
    70         int orig = skip;
    71         for (Method m : defc.getMethods()) {
    72             if (skip == results.length) {
    73                 break;
    74             }
    75             MemberName mn = new MemberName(m);
    76             results[skip++] = mn;
    77         }
    78         for (Constructor m : defc.getConstructors()) {
    79             if (skip == results.length) {
    80                 break;
    81             }
    82             MemberName mn = new MemberName(m);
    83             results[skip++] = mn;
    84         }
    85 //        for (Field m : defc.getFields()) {
    86 //            if (skip == results.length) {
    87 //                break;
    88 //            }
    89 //            MemberName mn = new MemberName(m);
    90 //            results[skip++] = mn;
    91 //        }
    92         return skip - orig;
    93     }
    94 
    95     /// Field layout queries parallel to sun.misc.Unsafe:
    96     static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
    97     static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
    98     static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
    99     static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
   100 
   101     /// MethodHandle support
   102 
   103     /// CallSite support
   104 
   105     /** Tell the JVM that we need to change the target of a CallSite. */
   106     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
   107     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
   108 
   109     static {
   110         // The JVM calls MethodHandleNatives.<clinit>.  Cascade the <clinit> calls as needed:
   111         MethodHandleImpl.initStatics();
   112 }
   113 
   114     // All compile-time constants go here.
   115     // There is an opportunity to check them against the JVM's idea of them.
   116     static class Constants {
   117         Constants() { } // static only
   118         // MethodHandleImpl
   119         static final int // for getConstant
   120                 GC_COUNT_GWT = 4,
   121                 GC_LAMBDA_SUPPORT = 5;
   122 
   123         // MemberName
   124         // The JVM uses values of -2 and above for vtable indexes.
   125         // Field values are simple positive offsets.
   126         // Ref: src/share/vm/oops/methodOop.hpp
   127         // This value is negative enough to avoid such numbers,
   128         // but not too negative.
   129         static final int
   130                 MN_IS_METHOD           = 0x00010000, // method (not constructor)
   131                 MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
   132                 MN_IS_FIELD            = 0x00040000, // field
   133                 MN_IS_TYPE             = 0x00080000, // nested type
   134                 MN_CALLER_SENSITIVE    = 0x00100000, // @CallerSensitive annotation detected
   135                 MN_REFERENCE_KIND_SHIFT = 24, // refKind
   136                 MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
   137                 // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
   138                 MN_SEARCH_SUPERCLASSES = 0x00100000,
   139                 MN_SEARCH_INTERFACES   = 0x00200000;
   140 
   141         /**
   142          * Basic types as encoded in the JVM.  These code values are not
   143          * intended for use outside this class.  They are used as part of
   144          * a private interface between the JVM and this class.
   145          */
   146         static final int
   147             T_BOOLEAN  =  4,
   148             T_CHAR     =  5,
   149             T_FLOAT    =  6,
   150             T_DOUBLE   =  7,
   151             T_BYTE     =  8,
   152             T_SHORT    =  9,
   153             T_INT      = 10,
   154             T_LONG     = 11,
   155             T_OBJECT   = 12,
   156             //T_ARRAY    = 13
   157             T_VOID     = 14,
   158             //T_ADDRESS  = 15
   159             T_ILLEGAL  = 99;
   160 
   161         /**
   162          * Constant pool entry types.
   163          */
   164         static final byte
   165             CONSTANT_Utf8                = 1,
   166             CONSTANT_Integer             = 3,
   167             CONSTANT_Float               = 4,
   168             CONSTANT_Long                = 5,
   169             CONSTANT_Double              = 6,
   170             CONSTANT_Class               = 7,
   171             CONSTANT_String              = 8,
   172             CONSTANT_Fieldref            = 9,
   173             CONSTANT_Methodref           = 10,
   174             CONSTANT_InterfaceMethodref  = 11,
   175             CONSTANT_NameAndType         = 12,
   176             CONSTANT_MethodHandle        = 15,  // JSR 292
   177             CONSTANT_MethodType          = 16,  // JSR 292
   178             CONSTANT_InvokeDynamic       = 18,
   179             CONSTANT_LIMIT               = 19;   // Limit to tags found in classfiles
   180 
   181         /**
   182          * Access modifier flags.
   183          */
   184         static final char
   185             ACC_PUBLIC                 = 0x0001,
   186             ACC_PRIVATE                = 0x0002,
   187             ACC_PROTECTED              = 0x0004,
   188             ACC_STATIC                 = 0x0008,
   189             ACC_FINAL                  = 0x0010,
   190             ACC_SYNCHRONIZED           = 0x0020,
   191             ACC_VOLATILE               = 0x0040,
   192             ACC_TRANSIENT              = 0x0080,
   193             ACC_NATIVE                 = 0x0100,
   194             ACC_INTERFACE              = 0x0200,
   195             ACC_ABSTRACT               = 0x0400,
   196             ACC_STRICT                 = 0x0800,
   197             ACC_SYNTHETIC              = 0x1000,
   198             ACC_ANNOTATION             = 0x2000,
   199             ACC_ENUM                   = 0x4000,
   200             // aliases:
   201             ACC_SUPER                  = ACC_SYNCHRONIZED,
   202             ACC_BRIDGE                 = ACC_VOLATILE,
   203             ACC_VARARGS                = ACC_TRANSIENT;
   204 
   205         /**
   206          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
   207          */
   208         static final byte
   209             REF_NONE                    = 0,  // null value
   210             REF_getField                = 1,
   211             REF_getStatic               = 2,
   212             REF_putField                = 3,
   213             REF_putStatic               = 4,
   214             REF_invokeVirtual           = 5,
   215             REF_invokeStatic            = 6,
   216             REF_invokeSpecial           = 7,
   217             REF_newInvokeSpecial        = 8,
   218             REF_invokeInterface         = 9,
   219             REF_LIMIT                  = 10;
   220     }
   221 
   222     static boolean refKindIsValid(int refKind) {
   223         return (refKind > REF_NONE && refKind < REF_LIMIT);
   224     }
   225     static boolean refKindIsField(byte refKind) {
   226         assert(refKindIsValid(refKind));
   227         return (refKind <= REF_putStatic);
   228     }
   229     static boolean refKindIsGetter(byte refKind) {
   230         assert(refKindIsValid(refKind));
   231         return (refKind <= REF_getStatic);
   232     }
   233     static boolean refKindIsSetter(byte refKind) {
   234         return refKindIsField(refKind) && !refKindIsGetter(refKind);
   235     }
   236     static boolean refKindIsMethod(byte refKind) {
   237         return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
   238     }
   239     static boolean refKindIsConstructor(byte refKind) {
   240         return (refKind == REF_newInvokeSpecial);
   241     }
   242     static boolean refKindHasReceiver(byte refKind) {
   243         assert(refKindIsValid(refKind));
   244         return (refKind & 1) != 0;
   245     }
   246     static boolean refKindIsStatic(byte refKind) {
   247         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
   248     }
   249     static boolean refKindDoesDispatch(byte refKind) {
   250         assert(refKindIsValid(refKind));
   251         return (refKind == REF_invokeVirtual ||
   252                 refKind == REF_invokeInterface);
   253     }
   254     static {
   255         final int HR_MASK = ((1 << REF_getField) |
   256                              (1 << REF_putField) |
   257                              (1 << REF_invokeVirtual) |
   258                              (1 << REF_invokeSpecial) |
   259                              (1 << REF_invokeInterface)
   260                             );
   261         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
   262             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
   263         }
   264     }
   265     static String refKindName(byte refKind) {
   266         assert(refKindIsValid(refKind));
   267         switch (refKind) {
   268         case REF_getField:          return "getField";
   269         case REF_getStatic:         return "getStatic";
   270         case REF_putField:          return "putField";
   271         case REF_putStatic:         return "putStatic";
   272         case REF_invokeVirtual:     return "invokeVirtual";
   273         case REF_invokeStatic:      return "invokeStatic";
   274         case REF_invokeSpecial:     return "invokeSpecial";
   275         case REF_newInvokeSpecial:  return "newInvokeSpecial";
   276         case REF_invokeInterface:   return "invokeInterface";
   277         default:                    return "REF_???";
   278         }
   279     }
   280 
   281     private static native int getNamedCon(int which, Object[] name);
   282     static boolean verifyConstants() {
   283         Object[] box = { null };
   284         for (int i = 0; ; i++) {
   285             box[0] = null;
   286             int vmval = getNamedCon(i, box);
   287             if (box[0] == null)  break;
   288             String name = (String) box[0];
   289             try {
   290                 Field con = Constants.class.getDeclaredField(name);
   291                 int jval = con.getInt(null);
   292                 if (jval == vmval)  continue;
   293                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
   294                 if (name.equals("CONV_OP_LIMIT")) {
   295                     System.err.println("warning: "+err);
   296                     continue;
   297                 }
   298                 throw new InternalError(err);
   299             } catch (IllegalAccessException ex) {
   300                 String err = (name+": JVM has "+vmval+" which Java does not define");
   301                 // ignore exotic ops the JVM cares about; we just wont issue them
   302                 //System.err.println("warning: "+err);
   303                 continue;
   304             }
   305         }
   306         return true;
   307     }
   308     static {
   309         assert(verifyConstants());
   310     }
   311 
   312     // Up-calls from the JVM.
   313     // These must NOT be public.
   314 
   315     /**
   316      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
   317      */
   318     static MemberName linkCallSite(Object callerObj,
   319                                    Object bootstrapMethodObj,
   320                                    Object nameObj, Object typeObj,
   321                                    Object staticArguments,
   322                                    Object[] appendixResult) {
   323         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
   324         Class<?> caller = (Class<?>)callerObj;
   325         String name = nameObj.toString().intern();
   326         MethodType type = (MethodType)typeObj;
   327         CallSite callSite = CallSite.makeSite(bootstrapMethod,
   328                                               name,
   329                                               type,
   330                                               staticArguments,
   331                                               caller);
   332         if (callSite instanceof ConstantCallSite) {
   333             appendixResult[0] = callSite.dynamicInvoker();
   334             return Invokers.linkToTargetMethod(type);
   335         } else {
   336             appendixResult[0] = callSite;
   337             return Invokers.linkToCallSiteMethod(type);
   338         }
   339     }
   340 
   341     /**
   342      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
   343      */
   344     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
   345         return MethodType.makeImpl(rtype, ptypes, true);
   346     }
   347 
   348     /**
   349      * The JVM wants to link a call site that requires a dynamic type check.
   350      * Name is a type-checking invoker, invokeExact or invoke.
   351      * Return a JVM method (MemberName) to handle the invoking.
   352      * The method assumes the following arguments on the stack:
   353      * 0: the method handle being invoked
   354      * 1-N: the arguments to the method handle invocation
   355      * N+1: an optional, implicitly added argument (typically the given MethodType)
   356      * <p>
   357      * The nominal method at such a call site is an instance of
   358      * a signature-polymorphic method (see @PolymorphicSignature).
   359      * Such method instances are user-visible entities which are
   360      * "split" from the generic placeholder method in {@code MethodHandle}.
   361      * (Note that the placeholder method is not identical with any of
   362      * its instances.  If invoked reflectively, is guaranteed to throw an
   363      * {@code UnsupportedOperationException}.)
   364      * If the signature-polymorphic method instance is ever reified,
   365      * it appears as a "copy" of the original placeholder
   366      * (a native final member of {@code MethodHandle}) except
   367      * that its type descriptor has shape required by the instance,
   368      * and the method instance is <em>not</em> varargs.
   369      * The method instance is also marked synthetic, since the
   370      * method (by definition) does not appear in Java source code.
   371      * <p>
   372      * The JVM is allowed to reify this method as instance metadata.
   373      * For example, {@code invokeBasic} is always reified.
   374      * But the JVM may instead call {@code linkMethod}.
   375      * If the result is an * ordered pair of a {@code (method, appendix)},
   376      * the method gets all the arguments (0..N inclusive)
   377      * plus the appendix (N+1), and uses the appendix to complete the call.
   378      * In this way, one reusable method (called a "linker method")
   379      * can perform the function of any number of polymorphic instance
   380      * methods.
   381      * <p>
   382      * Linker methods are allowed to be weakly typed, with any or
   383      * all references rewritten to {@code Object} and any primitives
   384      * (except {@code long}/{@code float}/{@code double})
   385      * rewritten to {@code int}.
   386      * A linker method is trusted to return a strongly typed result,
   387      * according to the specific method type descriptor of the
   388      * signature-polymorphic instance it is emulating.
   389      * This can involve (as necessary) a dynamic check using
   390      * data extracted from the appendix argument.
   391      * <p>
   392      * The JVM does not inspect the appendix, other than to pass
   393      * it verbatim to the linker method at every call.
   394      * This means that the JDK runtime has wide latitude
   395      * for choosing the shape of each linker method and its
   396      * corresponding appendix.
   397      * Linker methods should be generated from {@code LambdaForm}s
   398      * so that they do not become visible on stack traces.
   399      * <p>
   400      * The {@code linkMethod} call is free to omit the appendix
   401      * (returning null) and instead emulate the required function
   402      * completely in the linker method.
   403      * As a corner case, if N==255, no appendix is possible.
   404      * In this case, the method returned must be custom-generated to
   405      * to perform any needed type checking.
   406      * <p>
   407      * If the JVM does not reify a method at a call site, but instead
   408      * calls {@code linkMethod}, the corresponding call represented
   409      * in the bytecodes may mention a valid method which is not
   410      * representable with a {@code MemberName}.
   411      * Therefore, use cases for {@code linkMethod} tend to correspond to
   412      * special cases in reflective code such as {@code findVirtual}
   413      * or {@code revealDirect}.
   414      */
   415     static MemberName linkMethod(Class<?> callerClass, int refKind,
   416                                  Class<?> defc, String name, Object type,
   417                                  Object[] appendixResult) {
   418         if (!TRACE_METHOD_LINKAGE)
   419             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
   420         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
   421     }
   422     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
   423                                      Class<?> defc, String name, Object type,
   424                                      Object[] appendixResult) {
   425         try {
   426             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
   427                 return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
   428             }
   429         } catch (Throwable ex) {
   430             if (ex instanceof LinkageError)
   431                 throw (LinkageError) ex;
   432             else
   433                 throw new LinkageError(ex.getMessage(), ex);
   434         }
   435         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
   436     }
   437     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
   438         if (type instanceof MethodType)
   439             return (MethodType) type;
   440         else
   441             return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
   442     }
   443     // Tracing logic:
   444     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
   445                                         Class<?> defc, String name, Object type,
   446                                         Object[] appendixResult) {
   447         System.out.println("linkMethod "+defc.getName()+"."+
   448                            name+type+"/"+Integer.toHexString(refKind));
   449         try {
   450             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
   451             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
   452             return res;
   453         } catch (Throwable ex) {
   454             System.out.println("linkMethod => throw "+ex);
   455             throw ex;
   456         }
   457     }
   458 
   459 
   460     /**
   461      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
   462      * It will make an up-call to this method.  (Do not change the name or signature.)
   463      * The type argument is a Class for field requests and a MethodType for non-fields.
   464      * <p>
   465      * Recent versions of the JVM may also pass a resolved MemberName for the type.
   466      * In that case, the name is ignored and may be null.
   467      */
   468     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
   469                                                  Class<?> defc, String name, Object type) {
   470         try {
   471             Lookup lookup = IMPL_LOOKUP.in(callerClass);
   472             assert(refKindIsValid(refKind));
   473             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
   474         } catch (IllegalAccessException ex) {
   475             Throwable cause = ex.getCause();
   476             if (cause instanceof AbstractMethodError) {
   477                 throw (AbstractMethodError) cause;
   478             } else {
   479                 Error err = new IllegalAccessError(ex.getMessage());
   480                 throw initCauseFrom(err, ex);
   481             }
   482         } catch (NoSuchMethodException ex) {
   483             Error err = new NoSuchMethodError(ex.getMessage());
   484             throw initCauseFrom(err, ex);
   485         } catch (NoSuchFieldException ex) {
   486             Error err = new NoSuchFieldError(ex.getMessage());
   487             throw initCauseFrom(err, ex);
   488         } catch (ReflectiveOperationException ex) {
   489             Error err = new IncompatibleClassChangeError();
   490             throw initCauseFrom(err, ex);
   491         }
   492     }
   493 
   494     /**
   495      * Use best possible cause for err.initCause(), substituting the
   496      * cause for err itself if the cause has the same (or better) type.
   497      */
   498     static private Error initCauseFrom(Error err, Exception ex) {
   499         Throwable th = ex.getCause();
   500         if (err.getClass().isInstance(th))
   501            return (Error) th;
   502         err.initCause(th == null ? ex : th);
   503         return err;
   504     }
   505 
   506     /**
   507      * Is this method a caller-sensitive method?
   508      * I.e., does it call Reflection.getCallerClass or a similer method
   509      * to ask about the identity of its caller?
   510      */
   511     static boolean isCallerSensitive(MemberName mem) {
   512         if (!mem.isInvocable())  return false;  // fields are not caller sensitive
   513 
   514         return mem.isCallerSensitive() || canBeCalledVirtual(mem);
   515     }
   516 
   517     static boolean canBeCalledVirtual(MemberName mem) {
   518         assert(mem.isInvocable());
   519         Class<?> defc = mem.getDeclaringClass();
   520         switch (mem.getName()) {
   521         case "checkMemberAccess":
   522             return true; //canBeCalledVirtual(mem, java.lang.SecurityManager.class);
   523         case "getContextClassLoader":
   524             return canBeCalledVirtual(mem, java.lang.Thread.class);
   525         }
   526         return false;
   527     }
   528 
   529     static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
   530         Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
   531         if (symbolicRefClass == definingClass)  return true;
   532         if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
   533         return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
   534                 symbolicRefClass.isInterface());                     // Mdef implements Msym
   535     }
   536 }