1 /*
   2  * Copyright (c) 2008, 2012, 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.MethodHandleStatics.*;
  33 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  34 
  35 /**
  36  * The JVM interface for the method handles package is all here.
  37  * This is an interface internal and private to an implemetantion of JSR 292.
  38  * <em>This class is not part of the JSR 292 standard.</em>
  39  * @author jrose
  40  */
  41 class MethodHandleNatives {
  42 
  43     private MethodHandleNatives() { } // static only
  44 
  45     /// MemberName support
  46 
  47     static native void init(MemberName self, Object ref);
  48     static native void expand(MemberName self);
  49     static native MemberName resolve(MemberName self, Class<?> caller) throws LinkageError;
  50     static native int getMembers(Class<?> defc, String matchName, String matchSig,
  51             int matchFlags, Class<?> caller, int skip, MemberName[] results);
  52 
  53     /// Field layout queries parallel to sun.misc.Unsafe:
  54     static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
  55     static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
  56     static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
  57     static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
  58 
  59     /// MethodHandle support
  60 
  61     /** Fetch MH-related JVM parameter.
  62      *  which=0 retrieves MethodHandlePushLimit
  63      *  which=1 retrieves stack slot push size (in address units)
  64      */
  65     static native int getConstant(int which);
  66 
  67     static final boolean COUNT_GWT;
  68 
  69     /// CallSite support
  70 
  71     /** Tell the JVM that we need to change the target of a CallSite. */
  72     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
  73     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
  74 
  75     private static native void registerNatives();
  76     static {
  77         registerNatives();
  78         COUNT_GWT                   = getConstant(Constants.GC_COUNT_GWT) != 0;
  79 
  80         // The JVM calls MethodHandleNatives.<clinit>.  Cascade the <clinit> calls as needed:
  81         MethodHandleImpl.initStatics();
  82 }
  83 
  84     // All compile-time constants go here.
  85     // There is an opportunity to check them against the JVM's idea of them.
  86     static class Constants {
  87         Constants() { } // static only
  88         // MethodHandleImpl
  89         static final int // for getConstant
  90                 GC_COUNT_GWT = 4,
  91                 GC_LAMBDA_SUPPORT = 5;
  92 
  93         // MemberName
  94         // The JVM uses values of -2 and above for vtable indexes.
  95         // Field values are simple positive offsets.
  96         // Ref: src/share/vm/oops/methodOop.hpp
  97         // This value is negative enough to avoid such numbers,
  98         // but not too negative.
  99         static final int
 100                 MN_IS_METHOD           = 0x00010000, // method (not constructor)
 101                 MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
 102                 MN_IS_FIELD            = 0x00040000, // field
 103                 MN_IS_TYPE             = 0x00080000, // nested type
 104                 MN_REFERENCE_KIND_SHIFT = 24, // refKind
 105                 MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
 106                 // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
 107                 MN_SEARCH_SUPERCLASSES = 0x00100000,
 108                 MN_SEARCH_INTERFACES   = 0x00200000;
 109 
 110         /**
 111          * Basic types as encoded in the JVM.  These code values are not
 112          * intended for use outside this class.  They are used as part of
 113          * a private interface between the JVM and this class.
 114          */
 115         static final int
 116             T_BOOLEAN  =  4,
 117             T_CHAR     =  5,
 118             T_FLOAT    =  6,
 119             T_DOUBLE   =  7,
 120             T_BYTE     =  8,
 121             T_SHORT    =  9,
 122             T_INT      = 10,
 123             T_LONG     = 11,
 124             T_OBJECT   = 12,
 125             //T_ARRAY    = 13
 126             T_VOID     = 14,
 127             //T_ADDRESS  = 15
 128             T_ILLEGAL  = 99;
 129 
 130         /**
 131          * Constant pool entry types.
 132          */
 133         static final byte
 134             CONSTANT_Utf8                = 1,
 135             CONSTANT_Integer             = 3,
 136             CONSTANT_Float               = 4,
 137             CONSTANT_Long                = 5,
 138             CONSTANT_Double              = 6,
 139             CONSTANT_Class               = 7,
 140             CONSTANT_String              = 8,
 141             CONSTANT_Fieldref            = 9,
 142             CONSTANT_Methodref           = 10,
 143             CONSTANT_InterfaceMethodref  = 11,
 144             CONSTANT_NameAndType         = 12,
 145             CONSTANT_MethodHandle        = 15,  // JSR 292
 146             CONSTANT_MethodType          = 16,  // JSR 292
 147             CONSTANT_InvokeDynamic       = 18,
 148             CONSTANT_LIMIT               = 19;   // Limit to tags found in classfiles
 149 
 150         /**
 151          * Access modifier flags.
 152          */
 153         static final char
 154             ACC_PUBLIC                 = 0x0001,
 155             ACC_PRIVATE                = 0x0002,
 156             ACC_PROTECTED              = 0x0004,
 157             ACC_STATIC                 = 0x0008,
 158             ACC_FINAL                  = 0x0010,
 159             ACC_SYNCHRONIZED           = 0x0020,
 160             ACC_VOLATILE               = 0x0040,
 161             ACC_TRANSIENT              = 0x0080,
 162             ACC_NATIVE                 = 0x0100,
 163             ACC_INTERFACE              = 0x0200,
 164             ACC_ABSTRACT               = 0x0400,
 165             ACC_STRICT                 = 0x0800,
 166             ACC_SYNTHETIC              = 0x1000,
 167             ACC_ANNOTATION             = 0x2000,
 168             ACC_ENUM                   = 0x4000,
 169             // aliases:
 170             ACC_SUPER                  = ACC_SYNCHRONIZED,
 171             ACC_BRIDGE                 = ACC_VOLATILE,
 172             ACC_VARARGS                = ACC_TRANSIENT;
 173 
 174         /**
 175          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
 176          */
 177         static final byte
 178             REF_NONE                    = 0,  // null value
 179             REF_getField                = 1,
 180             REF_getStatic               = 2,
 181             REF_putField                = 3,
 182             REF_putStatic               = 4,
 183             REF_invokeVirtual           = 5,
 184             REF_invokeStatic            = 6,
 185             REF_invokeSpecial           = 7,
 186             REF_newInvokeSpecial        = 8,
 187             REF_invokeInterface         = 9,
 188             REF_LIMIT                  = 10;
 189     }
 190 
 191     static boolean refKindIsValid(int refKind) {
 192         return (refKind > REF_NONE && refKind < REF_LIMIT);
 193     }
 194     static boolean refKindIsField(byte refKind) {
 195         assert(refKindIsValid(refKind));
 196         return (refKind <= REF_putStatic);
 197     }
 198     static boolean refKindIsGetter(byte refKind) {
 199         assert(refKindIsValid(refKind));
 200         return (refKind <= REF_getStatic);
 201     }
 202     static boolean refKindIsSetter(byte refKind) {
 203         return refKindIsField(refKind) && !refKindIsGetter(refKind);
 204     }
 205     static boolean refKindIsMethod(byte refKind) {
 206         return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
 207     }
 208     static boolean refKindHasReceiver(byte refKind) {
 209         assert(refKindIsValid(refKind));
 210         return (refKind & 1) != 0;
 211     }
 212     static boolean refKindIsStatic(byte refKind) {
 213         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
 214     }
 215     static boolean refKindDoesDispatch(byte refKind) {
 216         assert(refKindIsValid(refKind));
 217         return (refKind == REF_invokeVirtual ||
 218                 refKind == REF_invokeInterface);
 219     }
 220     static {
 221         final int HR_MASK = ((1 << REF_getField) |
 222                              (1 << REF_putField) |
 223                              (1 << REF_invokeVirtual) |
 224                              (1 << REF_invokeSpecial) |
 225                              (1 << REF_invokeInterface)
 226                             );
 227         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
 228             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
 229         }
 230     }
 231     static String refKindName(byte refKind) {
 232         assert(refKindIsValid(refKind));
 233         return REFERENCE_KIND_NAME[refKind];
 234     }
 235     private static String[] REFERENCE_KIND_NAME = {
 236             null,
 237             "getField",
 238             "getStatic",
 239             "putField",
 240             "putStatic",
 241             "invokeVirtual",
 242             "invokeStatic",
 243             "invokeSpecial",
 244             "newInvokeSpecial",
 245             "invokeInterface"
 246     };
 247 
 248     private static native int getNamedCon(int which, Object[] name);
 249     static boolean verifyConstants() {
 250         Object[] box = { null };
 251         for (int i = 0; ; i++) {
 252             box[0] = null;
 253             int vmval = getNamedCon(i, box);
 254             if (box[0] == null)  break;
 255             String name = (String) box[0];
 256             try {
 257                 Field con = Constants.class.getDeclaredField(name);
 258                 int jval = con.getInt(null);
 259                 if (jval == vmval)  continue;
 260                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 261                 if (name.equals("CONV_OP_LIMIT")) {
 262                     System.err.println("warning: "+err);
 263                     continue;
 264                 }
 265                 throw new InternalError(err);
 266             } catch (NoSuchFieldException | IllegalAccessException ex) {
 267                 String err = (name+": JVM has "+vmval+" which Java does not define");
 268                 // ignore exotic ops the JVM cares about; we just wont issue them
 269                 //System.err.println("warning: "+err);
 270                 continue;
 271             }
 272         }
 273         return true;
 274     }
 275     static {
 276         assert(verifyConstants());
 277     }
 278 
 279     // Up-calls from the JVM.
 280     // These must NOT be public.
 281 
 282     /**
 283      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 284      */
 285     static MemberName linkCallSite(Object callerObj,
 286                                    Object bootstrapMethodObj,
 287                                    Object nameObj, Object typeObj,
 288                                    Object staticArguments,
 289                                    Object[] appendixResult) {
 290         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 291         Class<?> caller = (Class<?>)callerObj;
 292         String name = nameObj.toString().intern();
 293         MethodType type = (MethodType)typeObj;
 294         appendixResult[0] = CallSite.makeSite(bootstrapMethod,
 295                                               name,
 296                                               type,
 297                                               staticArguments,
 298                                               caller);
 299         return Invokers.linkToCallSiteMethod(type);
 300     }
 301 
 302     /**
 303      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 304      */
 305     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 306         return MethodType.makeImpl(rtype, ptypes, true);
 307     }
 308 
 309     /**
 310      * The JVM wants to link a call site that requires a dynamic type check.
 311      * Name is a type-checking invoker, invokeExact or invoke.
 312      * Return a JVM method (MemberName) to handle the invoking.
 313      * The method assumes the following arguments on the stack:
 314      * 0: the method handle being invoked
 315      * 1-N: the arguments to the method handle invocation
 316      * N+1: an implicitly added type argument (the given MethodType)
 317      */
 318     static MemberName linkMethod(Class<?> callerClass, int refKind,
 319                                  Class<?> defc, String name, Object type,
 320                                  Object[] appendixResult) {
 321         if (!TRACE_METHOD_LINKAGE)
 322             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 323         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
 324     }
 325     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
 326                                      Class<?> defc, String name, Object type,
 327                                      Object[] appendixResult) {
 328         try {
 329             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
 330                 switch (name) {
 331                 case "invoke":
 332                     return Invokers.genericInvokerMethod(fixMethodType(callerClass, type), appendixResult);
 333                 case "invokeExact":
 334                     return Invokers.exactInvokerMethod(fixMethodType(callerClass, type), appendixResult);
 335                 }
 336             }
 337         } catch (Throwable ex) {
 338             if (ex instanceof LinkageError)
 339                 throw (LinkageError) ex;
 340             else
 341                 throw new LinkageError(ex.getMessage(), ex);
 342         }
 343         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
 344     }
 345     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
 346         if (type instanceof MethodType)
 347             return (MethodType) type;
 348         else
 349             return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
 350     }
 351     // Tracing logic:
 352     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
 353                                         Class<?> defc, String name, Object type,
 354                                         Object[] appendixResult) {
 355         System.out.println("linkMethod "+defc.getName()+"."+
 356                            name+type+"/"+Integer.toHexString(refKind));
 357         try {
 358             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 359             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
 360             return res;
 361         } catch (Throwable ex) {
 362             System.out.println("linkMethod => throw "+ex);
 363             throw ex;
 364         }
 365     }
 366 
 367 
 368     /**
 369      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 370      * It will make an up-call to this method.  (Do not change the name or signature.)
 371      * The type argument is a Class for field requests and a MethodType for non-fields.
 372      * <p>
 373      * Recent versions of the JVM may also pass a resolved MemberName for the type.
 374      * In that case, the name is ignored and may be null.
 375      */
 376     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 377                                                  Class<?> defc, String name, Object type) {
 378         try {
 379             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 380             assert(refKindIsValid(refKind));
 381             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
 382         } catch (ReflectiveOperationException ex) {
 383             Error err = new IncompatibleClassChangeError();
 384             err.initCause(ex);
 385             throw err;
 386         }
 387     }
 388 
 389     /**
 390      * Is this method a caller-sensitive method?
 391      * I.e., does it call Reflection.getCallerClass or a similer method
 392      * to ask about the identity of its caller?
 393      */
 394     // FIXME: Replace this pattern match by an annotation @sun.reflect.CallerSensitive.
 395     static boolean isCallerSensitive(MemberName mem) {
 396         assert(mem.isInvocable());
 397         Class<?> defc = mem.getDeclaringClass();
 398         switch (mem.getName()) {
 399         case "doPrivileged":
 400             return defc == java.security.AccessController.class;
 401         case "getUnsafe":
 402             return defc == sun.misc.Unsafe.class;
 403         case "lookup":
 404             return defc == java.lang.invoke.MethodHandles.class;
 405         case "invoke":
 406             return defc == java.lang.reflect.Method.class;
 407         case "get":
 408         case "getBoolean":
 409         case "getByte":
 410         case "getChar":
 411         case "getShort":
 412         case "getInt":
 413         case "getLong":
 414         case "getFloat":
 415         case "getDouble":
 416         case "set":
 417         case "setBoolean":
 418         case "setByte":
 419         case "setChar":
 420         case "setShort":
 421         case "setInt":
 422         case "setLong":
 423         case "setFloat":
 424         case "setDouble":
 425             return defc == java.lang.reflect.Field.class;
 426         case "newInstance":
 427             if (defc == java.lang.reflect.Constructor.class)  return true;
 428             if (defc == java.lang.Class.class)  return true;
 429             break;
 430         case "forName":
 431         case "getClassLoader":
 432         case "getClasses":
 433         case "getFields":
 434         case "getMethods":
 435         case "getConstructors":
 436         case "getDeclaredClasses":
 437         case "getDeclaredFields":
 438         case "getDeclaredMethods":
 439         case "getDeclaredConstructors":
 440         case "getField":
 441         case "getMethod":
 442         case "getConstructor":
 443         case "getDeclaredField":
 444         case "getDeclaredMethod":
 445         case "getDeclaredConstructor":
 446             return defc == java.lang.Class.class;
 447         case "getConnection":
 448         case "getDriver":
 449         case "getDrivers":
 450         case "deregisterDriver":
 451             return defc == java.sql.DriverManager.class;
 452         case "newUpdater":
 453             if (defc == java.util.concurrent.atomic.AtomicIntegerFieldUpdater.class)  return true;
 454             if (defc == java.util.concurrent.atomic.AtomicLongFieldUpdater.class)  return true;
 455             if (defc == java.util.concurrent.atomic.AtomicReferenceFieldUpdater.class)  return true;
 456             break;
 457         case "getContextClassLoader":
 458             return defc == java.lang.Thread.class;
 459         case "getPackage":
 460         case "getPackages":
 461             return defc == java.lang.Package.class;
 462         case "getParent":
 463         case "getSystemClassLoader":
 464             return defc == java.lang.ClassLoader.class;
 465         case "load":
 466         case "loadLibrary":
 467             if (defc == java.lang.Runtime.class)  return true;
 468             if (defc == java.lang.System.class)  return true;
 469             break;
 470         case "getCallerClass":
 471             if (defc == sun.reflect.Reflection.class)  return true;
 472             if (defc == java.lang.System.class)  return true;
 473             break;
 474         case "getCallerClassLoader":
 475             return defc == java.lang.ClassLoader.class;
 476         case "getProxyClass":
 477         case "newProxyInstance":
 478             return defc == java.lang.reflect.Proxy.class;
 479         case "getBundle":
 480         case "clearCache":
 481             return defc == java.util.ResourceBundle.class;
 482         }
 483         return false;
 484     }
 485 }