Home » openjdk-7 » java.lang.invoke » [javadoc | source]

    1   /*
    2    * Copyright (c) 2008, 2011, 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.AccessibleObject;
   30   import java.lang.reflect.Field;
   31   import static java.lang.invoke.MethodHandleNatives.Constants.*;
   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 implemetantion 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       /// MethodName support
   45   
   46       static native void init(MemberName self, Object ref);
   47       static native void expand(MemberName self);
   48       static native void resolve(MemberName self, Class<?> caller);
   49       static native int getMembers(Class<?> defc, String matchName, String matchSig,
   50               int matchFlags, Class<?> caller, int skip, MemberName[] results);
   51   
   52       /// MethodHandle support
   53   
   54       /** Initialize the method handle to adapt the call. */
   55       static native void init(AdapterMethodHandle self, MethodHandle target, int argnum);
   56       /** Initialize the method handle to call the correct method, directly. */
   57       static native void init(BoundMethodHandle self, Object target, int argnum);
   58       /** Initialize the method handle to call as if by an invoke* instruction. */
   59       static native void init(DirectMethodHandle self, Object ref, boolean doDispatch, Class<?> caller);
   60   
   61       /** Initialize a method type, once per form. */
   62       static native void init(MethodType self);
   63   
   64       /** Tell the JVM about a class's bootstrap method. */
   65       static native void registerBootstrap(Class<?> caller, MethodHandle bootstrapMethod);
   66   
   67       /** Ask the JVM about a class's bootstrap method. */
   68       static native MethodHandle getBootstrap(Class<?> caller);
   69   
   70       /** Tell the JVM that we need to change the target of an invokedynamic. */
   71       static native void setCallSiteTarget(CallSite site, MethodHandle target);
   72   
   73       /** Fetch the vmtarget field.
   74        *  It will be sanitized as necessary to avoid exposing non-Java references.
   75        *  This routine is for debugging and reflection.
   76        */
   77       static native Object getTarget(MethodHandle self, int format);
   78   
   79       /** Fetch the name of the handled method, if available.
   80        *  This routine is for debugging and reflection.
   81        */
   82       static MemberName getMethodName(MethodHandle self) {
   83           return (MemberName) getTarget(self, ETF_METHOD_NAME);
   84       }
   85   
   86       /** Fetch the reflective version of the handled method, if available.
   87        */
   88       static AccessibleObject getTargetMethod(MethodHandle self) {
   89           return (AccessibleObject) getTarget(self, ETF_REFLECT_METHOD);
   90       }
   91   
   92       /** Fetch the target of this method handle.
   93        *  If it directly targets a method, return a MemberName for the method.
   94        *  If it is chained to another method handle, return that handle.
   95        */
   96       static Object getTargetInfo(MethodHandle self) {
   97           return getTarget(self, ETF_HANDLE_OR_METHOD_NAME);
   98       }
   99   
  100       static Object[] makeTarget(Class<?> defc, String name, String sig, int mods, Class<?> refc) {
  101           return new Object[] { defc, name, sig, mods, refc };
  102       }
  103   
  104       /** Fetch MH-related JVM parameter.
  105        *  which=0 retrieves MethodHandlePushLimit
  106        *  which=1 retrieves stack slot push size (in address units)
  107        */
  108       static native int getConstant(int which);
  109   
  110       /** Java copy of MethodHandlePushLimit in range 2..255. */
  111       static final int JVM_PUSH_LIMIT;
  112       /** JVM stack motion (in words) after one slot is pushed, usually -1.
  113        */
  114       static final int JVM_STACK_MOVE_UNIT;
  115   
  116       /** Which conv-ops are implemented by the JVM? */
  117       static final int CONV_OP_IMPLEMENTED_MASK;
  118       /** Derived mode flag.  Only false on some old JVM implementations. */
  119       static final boolean HAVE_RICOCHET_FRAMES;
  120   
  121       private static native void registerNatives();
  122       static {
  123           int     JVM_PUSH_LIMIT_;
  124           int     JVM_STACK_MOVE_UNIT_;
  125           int     CONV_OP_IMPLEMENTED_MASK_;
  126           try {
  127               registerNatives();
  128               JVM_PUSH_LIMIT_ = getConstant(Constants.GC_JVM_PUSH_LIMIT);
  129               JVM_STACK_MOVE_UNIT_ = getConstant(Constants.GC_JVM_STACK_MOVE_UNIT);
  130               CONV_OP_IMPLEMENTED_MASK_ = getConstant(Constants.GC_CONV_OP_IMPLEMENTED_MASK);
  131               //sun.reflect.Reflection.registerMethodsToFilter(MethodHandleImpl.class, "init");
  132           } catch (UnsatisfiedLinkError ee) {
  133               // ignore; if we use init() methods later we'll see linkage errors
  134               JVM_PUSH_LIMIT_ = 3;  // arbitrary
  135               JVM_STACK_MOVE_UNIT_ = -1;  // arbitrary
  136               CONV_OP_IMPLEMENTED_MASK_ = 0;
  137               JVM_PUSH_LIMIT = JVM_PUSH_LIMIT_;
  138               JVM_STACK_MOVE_UNIT = JVM_STACK_MOVE_UNIT_;
  139               throw ee;  // just die; hopeless to try to run with an older JVM
  140           }
  141           JVM_PUSH_LIMIT = JVM_PUSH_LIMIT_;
  142           JVM_STACK_MOVE_UNIT = JVM_STACK_MOVE_UNIT_;
  143           if (CONV_OP_IMPLEMENTED_MASK_ == 0)
  144               CONV_OP_IMPLEMENTED_MASK_ = DEFAULT_CONV_OP_IMPLEMENTED_MASK;
  145           CONV_OP_IMPLEMENTED_MASK = CONV_OP_IMPLEMENTED_MASK_;
  146           HAVE_RICOCHET_FRAMES = (CONV_OP_IMPLEMENTED_MASK & (1<<OP_COLLECT_ARGS)) != 0;
  147       }
  148   
  149       // All compile-time constants go here.
  150       // There is an opportunity to check them against the JVM's idea of them.
  151       static class Constants {
  152           Constants() { } // static only
  153           // MethodHandleImpl
  154           static final int // for getConstant
  155                   GC_JVM_PUSH_LIMIT = 0,
  156                   GC_JVM_STACK_MOVE_UNIT = 1,
  157                   GC_CONV_OP_IMPLEMENTED_MASK = 2;
  158           static final int
  159                   ETF_HANDLE_OR_METHOD_NAME = 0, // all available data (immediate MH or method)
  160                   ETF_DIRECT_HANDLE         = 1, // ultimate method handle (will be a DMH, may be self)
  161                   ETF_METHOD_NAME           = 2, // ultimate method as MemberName
  162                   ETF_REFLECT_METHOD        = 3; // ultimate method as java.lang.reflect object (sans refClass)
  163   
  164           // MemberName
  165           // The JVM uses values of -2 and above for vtable indexes.
  166           // Field values are simple positive offsets.
  167           // Ref: src/share/vm/oops/methodOop.hpp
  168           // This value is negative enough to avoid such numbers,
  169           // but not too negative.
  170           static final int
  171                   MN_IS_METHOD           = 0x00010000, // method (not constructor)
  172                   MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
  173                   MN_IS_FIELD            = 0x00040000, // field
  174                   MN_IS_TYPE             = 0x00080000, // nested type
  175                   MN_SEARCH_SUPERCLASSES = 0x00100000, // for MHN.getMembers
  176                   MN_SEARCH_INTERFACES   = 0x00200000, // for MHN.getMembers
  177                   VM_INDEX_UNINITIALIZED = -99;
  178   
  179           // BoundMethodHandle
  180           /** Constants for decoding the vmargslot field, which contains 2 values. */
  181           static final int
  182               ARG_SLOT_PUSH_SHIFT = 16,
  183               ARG_SLOT_MASK = (1<<ARG_SLOT_PUSH_SHIFT)-1;
  184   
  185           // AdapterMethodHandle
  186           /** Conversions recognized by the JVM.
  187            *  They must align with the constants in java.lang.invoke.AdapterMethodHandle,
  188            *  in the JVM file hotspot/src/share/vm/classfile/javaClasses.hpp.
  189            */
  190           static final int
  191               OP_RETYPE_ONLY   = 0x0, // no argument changes; straight retype
  192               OP_RETYPE_RAW    = 0x1, // straight retype, trusted (void->int, Object->T)
  193               OP_CHECK_CAST    = 0x2, // ref-to-ref conversion; requires a Class argument
  194               OP_PRIM_TO_PRIM  = 0x3, // converts from one primitive to another
  195               OP_REF_TO_PRIM   = 0x4, // unboxes a wrapper to produce a primitive
  196               OP_PRIM_TO_REF   = 0x5, // boxes a primitive into a wrapper
  197               OP_SWAP_ARGS     = 0x6, // swap arguments (vminfo is 2nd arg)
  198               OP_ROT_ARGS      = 0x7, // rotate arguments (vminfo is displaced arg)
  199               OP_DUP_ARGS      = 0x8, // duplicates one or more arguments (at TOS)
  200               OP_DROP_ARGS     = 0x9, // remove one or more argument slots
  201               OP_COLLECT_ARGS  = 0xA, // combine arguments using an auxiliary function
  202               OP_SPREAD_ARGS   = 0xB, // expand in place a varargs array (of known size)
  203               OP_FOLD_ARGS     = 0xC, // combine but do not remove arguments; prepend result
  204               //OP_UNUSED_13   = 0xD, // unused code, perhaps for reified argument lists
  205               CONV_OP_LIMIT    = 0xE; // limit of CONV_OP enumeration
  206           /** Shift and mask values for decoding the AMH.conversion field.
  207            *  These numbers are shared with the JVM for creating AMHs.
  208            */
  209           static final int
  210               CONV_OP_MASK     = 0xF00, // this nybble contains the conversion op field
  211               CONV_TYPE_MASK   = 0x0F,  // fits T_ADDRESS and below
  212               CONV_VMINFO_MASK = 0x0FF, // LSB is reserved for JVM use
  213               CONV_VMINFO_SHIFT     =  0, // position of bits in CONV_VMINFO_MASK
  214               CONV_OP_SHIFT         =  8, // position of bits in CONV_OP_MASK
  215               CONV_DEST_TYPE_SHIFT  = 12, // byte 2 has the adapter BasicType (if needed)
  216               CONV_SRC_TYPE_SHIFT   = 16, // byte 2 has the source BasicType (if needed)
  217               CONV_STACK_MOVE_SHIFT = 20, // high 12 bits give signed SP change
  218               CONV_STACK_MOVE_MASK  = (1 << (32 - CONV_STACK_MOVE_SHIFT)) - 1;
  219   
  220           /** Which conv-ops are implemented by the JVM? */
  221           static final int DEFAULT_CONV_OP_IMPLEMENTED_MASK =
  222                   // Value to use if the corresponding JVM query fails.
  223                   ((1<<OP_RETYPE_ONLY)
  224                   |(1<<OP_RETYPE_RAW)
  225                   |(1<<OP_CHECK_CAST)
  226                   |(1<<OP_PRIM_TO_PRIM)
  227                   |(1<<OP_REF_TO_PRIM)
  228                   |(1<<OP_SWAP_ARGS)
  229                   |(1<<OP_ROT_ARGS)
  230                   |(1<<OP_DUP_ARGS)
  231                   |(1<<OP_DROP_ARGS)
  232                   //|(1<<OP_SPREAD_ARGS)
  233                   );
  234   
  235           /**
  236            * Basic types as encoded in the JVM.  These code values are not
  237            * intended for use outside this class.  They are used as part of
  238            * a private interface between the JVM and this class.
  239            */
  240           static final int
  241               T_BOOLEAN  =  4,
  242               T_CHAR     =  5,
  243               T_FLOAT    =  6,
  244               T_DOUBLE   =  7,
  245               T_BYTE     =  8,
  246               T_SHORT    =  9,
  247               T_INT      = 10,
  248               T_LONG     = 11,
  249               T_OBJECT   = 12,
  250               //T_ARRAY    = 13
  251               T_VOID     = 14,
  252               //T_ADDRESS  = 15
  253               T_ILLEGAL  = 99;
  254   
  255           /**
  256            * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
  257            */
  258           static final int
  259               REF_getField                = 1,
  260               REF_getStatic               = 2,
  261               REF_putField                = 3,
  262               REF_putStatic               = 4,
  263               REF_invokeVirtual           = 5,
  264               REF_invokeStatic            = 6,
  265               REF_invokeSpecial           = 7,
  266               REF_newInvokeSpecial        = 8,
  267               REF_invokeInterface         = 9;
  268       }
  269   
  270       private static native int getNamedCon(int which, Object[] name);
  271       static boolean verifyConstants() {
  272           Object[] box = { null };
  273           for (int i = 0; ; i++) {
  274               box[0] = null;
  275               int vmval = getNamedCon(i, box);
  276               if (box[0] == null)  break;
  277               String name = (String) box[0];
  278               try {
  279                   Field con = Constants.class.getDeclaredField(name);
  280                   int jval = con.getInt(null);
  281                   if (jval == vmval)  continue;
  282                   String err = (name+": JVM has "+vmval+" while Java has "+jval);
  283                   if (name.equals("CONV_OP_LIMIT")) {
  284                       System.err.println("warning: "+err);
  285                       continue;
  286                   }
  287                   throw new InternalError(err);
  288               } catch (Exception ex) {
  289                   if (ex instanceof NoSuchFieldException) {
  290                       String err = (name+": JVM has "+vmval+" which Java does not define");
  291                       // ignore exotic ops the JVM cares about; we just wont issue them
  292                       if (name.startsWith("OP_") || name.startsWith("GC_")) {
  293                           System.err.println("warning: "+err);
  294                           continue;
  295                       }
  296                   }
  297                   throw new InternalError(name+": access failed, got "+ex);
  298               }
  299           }
  300           return true;
  301       }
  302       static {
  303           assert(verifyConstants());
  304       }
  305   
  306       // Up-calls from the JVM.
  307       // These must NOT be public.
  308   
  309       /**
  310        * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
  311        */
  312       static CallSite makeDynamicCallSite(MethodHandle bootstrapMethod,
  313                                           String name, MethodType type,
  314                                           Object info,
  315                                           MemberName callerMethod, int callerBCI) {
  316           return CallSite.makeSite(bootstrapMethod, name, type, info, callerMethod, callerBCI);
  317       }
  318   
  319       /**
  320        * Called by the JVM to check the length of a spread array.
  321        */
  322       static void checkSpreadArgument(Object av, int n) {
  323           MethodHandleStatics.checkSpreadArgument(av, n);
  324       }
  325   
  326       /**
  327        * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
  328        */
  329       static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
  330           return MethodType.makeImpl(rtype, ptypes, true);
  331       }
  332   
  333       /**
  334        * The JVM wants to use a MethodType with inexact invoke.  Give the runtime fair warning.
  335        */
  336       static void notifyGenericMethodType(MethodType type) {
  337           type.form().notifyGenericMethodType();
  338       }
  339   
  340       /**
  341        * The JVM wants to raise an exception.  Here's the path.
  342        */
  343       static void raiseException(int code, Object actual, Object required) {
  344           String message = null;
  345           switch (code) {
  346           case 190: // arraylength
  347               try {
  348                   String reqLength = "";
  349                   if (required instanceof AdapterMethodHandle) {
  350                       int conv = ((AdapterMethodHandle)required).getConversion();
  351                       int spChange = AdapterMethodHandle.extractStackMove(conv);
  352                       reqLength = " of length "+(spChange+1);
  353                   }
  354                   int actualLength = actual == null ? 0 : java.lang.reflect.Array.getLength(actual);
  355                   message = "required array"+reqLength+", but encountered wrong length "+actualLength;
  356                   break;
  357               } catch (IllegalArgumentException ex) {
  358               }
  359               required = Object[].class;  // should have been an array
  360               code = 192; // checkcast
  361               break;
  362           case 191: // athrow
  363               // JVM is asking us to wrap an exception which happened during resolving
  364               if (required == BootstrapMethodError.class) {
  365                   throw new BootstrapMethodError((Throwable) actual);
  366               }
  367               break;
  368           }
  369           // disregard the identity of the actual object, if it is not a class:
  370           if (message == null) {
  371               if (!(actual instanceof Class) && !(actual instanceof MethodType))
  372                   actual = actual.getClass();
  373              if (actual != null)
  374                  message = "required "+required+" but encountered "+actual;
  375              else
  376                  message = "required "+required;
  377           }
  378           switch (code) {
  379           case 190: // arraylength
  380               throw new ArrayIndexOutOfBoundsException(message);
  381           case 50: //_aaload
  382               throw new ClassCastException(message);
  383           case 192: // checkcast
  384               throw new ClassCastException(message);
  385           default:
  386               throw new InternalError("unexpected code "+code+": "+message);
  387           }
  388       }
  389   
  390       /**
  391        * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
  392        * It will make an up-call to this method.  (Do not change the name or signature.)
  393        */
  394       static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
  395                                                    Class<?> defc, String name, Object type) {
  396           try {
  397               Lookup lookup = IMPL_LOOKUP.in(callerClass);
  398               return lookup.linkMethodHandleConstant(refKind, defc, name, type);
  399           } catch (ReflectiveOperationException ex) {
  400               Error err = new IncompatibleClassChangeError();
  401               err.initCause(ex);
  402               throw err;
  403           }
  404       }
  405   
  406       /**
  407        * This assertion marks code which was written before ricochet frames were implemented.
  408        * Such code will go away when the ports catch up.
  409        */
  410       static boolean workaroundWithoutRicochetFrames() {
  411           assert(!HAVE_RICOCHET_FRAMES) : "this code should not be executed if `-XX:+UseRicochetFrames is enabled";
  412           return true;
  413       }
  414   }

Home » openjdk-7 » java.lang.invoke » [javadoc | source]