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