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