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