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     static final int OP_ROT_ARGS_DOWN_LIMIT_BIAS;
 122 
 123     static final boolean COUNT_GWT;
 124 
 125     private static native void registerNatives();
 126     static {
 127         registerNatives();
 128         int k;
 129         JVM_PUSH_LIMIT              = getConstant(Constants.GC_JVM_PUSH_LIMIT);
 130         JVM_STACK_MOVE_UNIT         = getConstant(Constants.GC_JVM_STACK_MOVE_UNIT);
 131         k                           = getConstant(Constants.GC_CONV_OP_IMPLEMENTED_MASK);
 132         CONV_OP_IMPLEMENTED_MASK    = (k != 0) ? k : DEFAULT_CONV_OP_IMPLEMENTED_MASK;
 133         k                           = getConstant(Constants.GC_OP_ROT_ARGS_DOWN_LIMIT_BIAS);
 134         OP_ROT_ARGS_DOWN_LIMIT_BIAS = (k != 0) ? (byte)k : -1;
 135         HAVE_RICOCHET_FRAMES        = (CONV_OP_IMPLEMENTED_MASK & (1<<OP_COLLECT_ARGS)) != 0;
 136         COUNT_GWT                   = getConstant(Constants.GC_COUNT_GWT) != 0;
 137         //sun.reflect.Reflection.registerMethodsToFilter(MethodHandleImpl.class, "init");
 138     }
 139 
 140     // All compile-time constants go here.
 141     // There is an opportunity to check them against the JVM's idea of them.
 142     static class Constants {
 143         Constants() { } // static only
 144         // MethodHandleImpl
 145         static final int // for getConstant
 146                 GC_JVM_PUSH_LIMIT = 0,
 147                 GC_JVM_STACK_MOVE_UNIT = 1,
 148                 GC_CONV_OP_IMPLEMENTED_MASK = 2,
 149                 GC_OP_ROT_ARGS_DOWN_LIMIT_BIAS = 3,
 150                 GC_COUNT_GWT = 4;
 151         static final int
 152                 ETF_HANDLE_OR_METHOD_NAME = 0, // all available data (immediate MH or method)
 153                 ETF_DIRECT_HANDLE         = 1, // ultimate method handle (will be a DMH, may be self)
 154                 ETF_METHOD_NAME           = 2, // ultimate method as MemberName
 155                 ETF_REFLECT_METHOD        = 3; // ultimate method as java.lang.reflect object (sans refClass)
 156 
 157         // MemberName
 158         // The JVM uses values of -2 and above for vtable indexes.
 159         // Field values are simple positive offsets.
 160         // Ref: src/share/vm/oops/methodOop.hpp
 161         // This value is negative enough to avoid such numbers,
 162         // but not too negative.
 163         static final int
 164                 MN_IS_METHOD           = 0x00010000, // method (not constructor)
 165                 MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
 166                 MN_IS_FIELD            = 0x00040000, // field
 167                 MN_IS_TYPE             = 0x00080000, // nested type
 168                 MN_SEARCH_SUPERCLASSES = 0x00100000, // for MHN.getMembers
 169                 MN_SEARCH_INTERFACES   = 0x00200000, // for MHN.getMembers
 170                 VM_INDEX_UNINITIALIZED = -99;
 171 
 172         // BoundMethodHandle
 173         /** Constants for decoding the vmargslot field, which contains 2 values. */
 174         static final int
 175             ARG_SLOT_PUSH_SHIFT = 16,
 176             ARG_SLOT_MASK = (1<<ARG_SLOT_PUSH_SHIFT)-1;
 177 
 178         // AdapterMethodHandle
 179         /** Conversions recognized by the JVM.
 180          *  They must align with the constants in java.lang.invoke.AdapterMethodHandle,
 181          *  in the JVM file hotspot/src/share/vm/classfile/javaClasses.hpp.
 182          */
 183         static final int
 184             OP_RETYPE_ONLY   = 0x0, // no argument changes; straight retype
 185             OP_RETYPE_RAW    = 0x1, // straight retype, trusted (void->int, Object->T)
 186             OP_CHECK_CAST    = 0x2, // ref-to-ref conversion; requires a Class argument
 187             OP_PRIM_TO_PRIM  = 0x3, // converts from one primitive to another
 188             OP_REF_TO_PRIM   = 0x4, // unboxes a wrapper to produce a primitive
 189             OP_PRIM_TO_REF   = 0x5, // boxes a primitive into a wrapper
 190             OP_SWAP_ARGS     = 0x6, // swap arguments (vminfo is 2nd arg)
 191             OP_ROT_ARGS      = 0x7, // rotate arguments (vminfo is displaced arg)
 192             OP_DUP_ARGS      = 0x8, // duplicates one or more arguments (at TOS)
 193             OP_DROP_ARGS     = 0x9, // remove one or more argument slots
 194             OP_COLLECT_ARGS  = 0xA, // combine arguments using an auxiliary function
 195             OP_SPREAD_ARGS   = 0xB, // expand in place a varargs array (of known size)
 196             OP_FOLD_ARGS     = 0xC, // combine but do not remove arguments; prepend result
 197             //OP_UNUSED_13   = 0xD, // unused code, perhaps for reified argument lists
 198             CONV_OP_LIMIT    = 0xE; // limit of CONV_OP enumeration
 199         /** Shift and mask values for decoding the AMH.conversion field.
 200          *  These numbers are shared with the JVM for creating AMHs.
 201          */
 202         static final int
 203             CONV_OP_MASK     = 0xF00, // this nybble contains the conversion op field
 204             CONV_TYPE_MASK   = 0x0F,  // fits T_ADDRESS and below
 205             CONV_VMINFO_MASK = 0x0FF, // LSB is reserved for JVM use
 206             CONV_VMINFO_SHIFT     =  0, // position of bits in CONV_VMINFO_MASK
 207             CONV_OP_SHIFT         =  8, // position of bits in CONV_OP_MASK
 208             CONV_DEST_TYPE_SHIFT  = 12, // byte 2 has the adapter BasicType (if needed)
 209             CONV_SRC_TYPE_SHIFT   = 16, // byte 2 has the source BasicType (if needed)
 210             CONV_STACK_MOVE_SHIFT = 20, // high 12 bits give signed SP change
 211             CONV_STACK_MOVE_MASK  = (1 << (32 - CONV_STACK_MOVE_SHIFT)) - 1;
 212 
 213         /** Which conv-ops are implemented by the JVM? */
 214         static final int DEFAULT_CONV_OP_IMPLEMENTED_MASK =
 215                 // Value to use if the corresponding JVM query fails.
 216                 ((1<<OP_RETYPE_ONLY)
 217                 |(1<<OP_RETYPE_RAW)
 218                 |(1<<OP_CHECK_CAST)
 219                 |(1<<OP_PRIM_TO_PRIM)
 220                 |(1<<OP_REF_TO_PRIM)
 221                 |(1<<OP_SWAP_ARGS)
 222                 |(1<<OP_ROT_ARGS)
 223                 |(1<<OP_DUP_ARGS)
 224                 |(1<<OP_DROP_ARGS)
 225                 //|(1<<OP_SPREAD_ARGS)
 226                 );
 227 
 228         /**
 229          * Basic types as encoded in the JVM.  These code values are not
 230          * intended for use outside this class.  They are used as part of
 231          * a private interface between the JVM and this class.
 232          */
 233         static final int
 234             T_BOOLEAN  =  4,
 235             T_CHAR     =  5,
 236             T_FLOAT    =  6,
 237             T_DOUBLE   =  7,
 238             T_BYTE     =  8,
 239             T_SHORT    =  9,
 240             T_INT      = 10,
 241             T_LONG     = 11,
 242             T_OBJECT   = 12,
 243             //T_ARRAY    = 13
 244             T_VOID     = 14,
 245             //T_ADDRESS  = 15
 246             T_ILLEGAL  = 99;
 247 
 248         /**
 249          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
 250          */
 251         static final int
 252             REF_getField                = 1,
 253             REF_getStatic               = 2,
 254             REF_putField                = 3,
 255             REF_putStatic               = 4,
 256             REF_invokeVirtual           = 5,
 257             REF_invokeStatic            = 6,
 258             REF_invokeSpecial           = 7,
 259             REF_newInvokeSpecial        = 8,
 260             REF_invokeInterface         = 9;
 261     }
 262 
 263     private static native int getNamedCon(int which, Object[] name);
 264     static boolean verifyConstants() {
 265         Object[] box = { null };
 266         for (int i = 0; ; i++) {
 267             box[0] = null;
 268             int vmval = getNamedCon(i, box);
 269             if (box[0] == null)  break;
 270             String name = (String) box[0];
 271             try {
 272                 Field con = Constants.class.getDeclaredField(name);
 273                 int jval = con.getInt(null);
 274                 if (jval == vmval)  continue;
 275                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 276                 if (name.equals("CONV_OP_LIMIT")) {
 277                     System.err.println("warning: "+err);
 278                     continue;
 279                 }
 280                 throw new InternalError(err);
 281             } catch (Exception ex) {
 282                 if (ex instanceof NoSuchFieldException) {
 283                     String err = (name+": JVM has "+vmval+" which Java does not define");
 284                     // ignore exotic ops the JVM cares about; we just wont issue them
 285                     if (name.startsWith("OP_") || name.startsWith("GC_")) {
 286                         System.err.println("warning: "+err);
 287                         continue;
 288                     }
 289                 }
 290                 throw new InternalError(name+": access failed, got "+ex);
 291             }
 292         }
 293         return true;
 294     }
 295     static {
 296         assert(verifyConstants());
 297     }
 298 
 299     // Up-calls from the JVM.
 300     // These must NOT be public.
 301 
 302     /**
 303      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 304      */
 305     static CallSite makeDynamicCallSite(MethodHandle bootstrapMethod,
 306                                         String name, MethodType type,
 307                                         Object info,
 308                                         MemberName callerMethod, int callerBCI) {
 309         return CallSite.makeSite(bootstrapMethod, name, type, info, callerMethod, callerBCI);
 310     }
 311 
 312     /**
 313      * Called by the JVM to check the length of a spread array.
 314      */
 315     static void checkSpreadArgument(Object av, int n) {
 316         MethodHandleStatics.checkSpreadArgument(av, n);
 317     }
 318 
 319     /**
 320      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 321      */
 322     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 323         return MethodType.makeImpl(rtype, ptypes, true);
 324     }
 325 
 326     /**
 327      * The JVM wants to use a MethodType with inexact invoke.  Give the runtime fair warning.
 328      */
 329     static void notifyGenericMethodType(MethodType type) {
 330         type.form().notifyGenericMethodType();
 331     }
 332 
 333     /**
 334      * The JVM wants to raise an exception.  Here's the path.
 335      */
 336     static void raiseException(int code, Object actual, Object required) {
 337         String message = null;
 338         switch (code) {
 339         case 190: // arraylength
 340             try {
 341                 String reqLength = "";
 342                 if (required instanceof AdapterMethodHandle) {
 343                     int conv = ((AdapterMethodHandle)required).getConversion();
 344                     int spChange = AdapterMethodHandle.extractStackMove(conv);
 345                     reqLength = " of length "+(spChange+1);
 346                 }
 347                 int actualLength = actual == null ? 0 : java.lang.reflect.Array.getLength(actual);
 348                 message = "required array"+reqLength+", but encountered wrong length "+actualLength;
 349                 break;
 350             } catch (IllegalArgumentException ex) {
 351             }
 352             required = Object[].class;  // should have been an array
 353             code = 192; // checkcast
 354             break;
 355         case 191: // athrow
 356             // JVM is asking us to wrap an exception which happened during resolving
 357             if (required == BootstrapMethodError.class) {
 358                 throw new BootstrapMethodError((Throwable) actual);
 359             }
 360             break;
 361         }
 362         // disregard the identity of the actual object, if it is not a class:
 363         if (message == null) {
 364             if (!(actual instanceof Class) && !(actual instanceof MethodType))
 365                 actual = actual.getClass();
 366            if (actual != null)
 367                message = "required "+required+" but encountered "+actual;
 368            else
 369                message = "required "+required;
 370         }
 371         switch (code) {
 372         case 190: // arraylength
 373             throw new ArrayIndexOutOfBoundsException(message);
 374         case 50: //_aaload
 375             throw new ClassCastException(message);
 376         case 192: // checkcast
 377             throw new ClassCastException(message);
 378         default:
 379             throw new InternalError("unexpected code "+code+": "+message);
 380         }
 381     }
 382 
 383     /**
 384      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 385      * It will make an up-call to this method.  (Do not change the name or signature.)
 386      */
 387     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 388                                                  Class<?> defc, String name, Object type) {
 389         try {
 390             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 391             return lookup.linkMethodHandleConstant(refKind, defc, name, type);
 392         } catch (ReflectiveOperationException ex) {
 393             Error err = new IncompatibleClassChangeError();
 394             err.initCause(ex);
 395             throw err;
 396         }
 397     }
 398 }