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 java.lang.invoke.MethodHandles.Lookup;
  29 import java.lang.reflect.Field;
  30 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  31 import static java.lang.invoke.MethodHandleStatics.*;
  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 implementation 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     /// MemberName support
  45 
  46     static native void init(MemberName self, Object ref);
  47     static native void expand(MemberName self);
  48     static native MemberName resolve(MemberName self, Class<?> caller) throws LinkageError;
  49     static native int getMembers(Class<?> defc, String matchName, String matchSig,
  50             int matchFlags, Class<?> caller, int skip, MemberName[] results);
  51 
  52     /// Field layout queries parallel to sun.misc.Unsafe:
  53     static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
  54     static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
  55     static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
  56     static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
  57 
  58     /// MethodHandle support
  59 
  60     /** Fetch MH-related JVM parameter.
  61      *  which=0 retrieves MethodHandlePushLimit
  62      *  which=1 retrieves stack slot push size (in address units)
  63      */
  64     static native int getConstant(int which);
  65 
  66     static final boolean COUNT_GWT;
  67 
  68     /// CallSite support
  69 
  70     /** Tell the JVM that we need to change the target of a CallSite. */
  71     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
  72     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
  73 
  74     private static native void registerNatives();
  75     static {
  76         registerNatives();
  77         COUNT_GWT                   = getConstant(Constants.GC_COUNT_GWT) != 0;
  78 
  79         // The JVM calls MethodHandleNatives.<clinit>.  Cascade the <clinit> calls as needed:
  80         MethodHandleImpl.initStatics();
  81     }
  82 
  83     // All compile-time constants go here.
  84     // There is an opportunity to check them against the JVM's idea of them.



  85     static class Constants {
  86         Constants() { } // static only
  87         // MethodHandleImpl
  88         static final int // for getConstant
  89                 GC_COUNT_GWT = 4,
  90                 GC_LAMBDA_SUPPORT = 5;
  91 
  92         // MemberName
  93         // The JVM uses values of -2 and above for vtable indexes.
  94         // Field values are simple positive offsets.
  95         // Ref: src/share/vm/oops/methodOop.hpp
  96         // This value is negative enough to avoid such numbers,
  97         // but not too negative.
  98         static final int
  99                 MN_IS_METHOD           = 0x00010000, // method (not constructor)
 100                 MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
 101                 MN_IS_FIELD            = 0x00040000, // field
 102                 MN_IS_TYPE             = 0x00080000, // nested type
 103                 MN_CALLER_SENSITIVE    = 0x00100000, // @CallerSensitive annotation detected
 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 refKindIsConstructor(byte refKind) {
 209         return (refKind == REF_newInvokeSpecial);
 210     }
 211     static boolean refKindHasReceiver(byte refKind) {
 212         assert(refKindIsValid(refKind));
 213         return (refKind & 1) != 0;
 214     }
 215     static boolean refKindIsStatic(byte refKind) {
 216         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
 217     }
 218     static boolean refKindDoesDispatch(byte refKind) {
 219         assert(refKindIsValid(refKind));
 220         return (refKind == REF_invokeVirtual ||
 221                 refKind == REF_invokeInterface);
 222     }
 223     static {
 224         final int HR_MASK = ((1 << REF_getField) |
 225                              (1 << REF_putField) |
 226                              (1 << REF_invokeVirtual) |
 227                              (1 << REF_invokeSpecial) |
 228                              (1 << REF_invokeInterface)
 229                             );
 230         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
 231             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
 232         }
 233     }
 234     static String refKindName(byte refKind) {
 235         assert(refKindIsValid(refKind));
 236         switch (refKind) {
 237         case REF_getField:          return "getField";
 238         case REF_getStatic:         return "getStatic";
 239         case REF_putField:          return "putField";
 240         case REF_putStatic:         return "putStatic";
 241         case REF_invokeVirtual:     return "invokeVirtual";
 242         case REF_invokeStatic:      return "invokeStatic";
 243         case REF_invokeSpecial:     return "invokeSpecial";
 244         case REF_newInvokeSpecial:  return "newInvokeSpecial";
 245         case REF_invokeInterface:   return "invokeInterface";
 246         default:                    return "REF_???";
 247         }
 248     }
 249 
 250     private static native int getNamedCon(int which, Object[] name);
 251     static boolean verifyConstants() {
 252         Object[] box = { null };
 253         for (int i = 0; ; i++) {
 254             box[0] = null;
 255             int vmval = getNamedCon(i, box);
 256             if (box[0] == null)  break;
 257             String name = (String) box[0];
 258             try {
 259                 Field con = Constants.class.getDeclaredField(name);
 260                 int jval = con.getInt(null);
 261                 if (jval == vmval)  continue;
 262                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 263                 if (name.equals("CONV_OP_LIMIT")) {
 264                     System.err.println("warning: "+err);
 265                     continue;
 266                 }
 267                 throw new InternalError(err);
 268             } catch (NoSuchFieldException | IllegalAccessException ex) {
 269                 String err = (name+": JVM has "+vmval+" which Java does not define");
 270                 // ignore exotic ops the JVM cares about; we just wont issue them
 271                 //System.err.println("warning: "+err);
 272                 continue;
 273             }
 274         }
 275         return true;
 276     }
 277     static {
 278         assert(verifyConstants());
 279     }
 280 
 281     // Up-calls from the JVM.
 282     // These must NOT be public.
 283 
 284     /**
 285      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 286      */
 287     static MemberName linkCallSite(Object callerObj,
 288                                    Object bootstrapMethodObj,
 289                                    Object nameObj, Object typeObj,
 290                                    Object staticArguments,
 291                                    Object[] appendixResult) {
 292         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 293         Class<?> caller = (Class<?>)callerObj;
 294         String name = nameObj.toString().intern();
 295         MethodType type = (MethodType)typeObj;
 296         if (!TRACE_METHOD_LINKAGE)
 297             return linkCallSiteImpl(caller, bootstrapMethod, name, type,
 298                                     staticArguments, appendixResult);
 299         return linkCallSiteTracing(caller, bootstrapMethod, name, type,
 300                                    staticArguments, appendixResult);
 301     }
 302     static MemberName linkCallSiteImpl(Class<?> caller,
 303                                        MethodHandle bootstrapMethod,
 304                                        String name, MethodType type,
 305                                        Object staticArguments,
 306                                        Object[] appendixResult) {
 307         CallSite callSite = CallSite.makeSite(bootstrapMethod,
 308                                               name,
 309                                               type,
 310                                               staticArguments,
 311                                               caller);
 312         if (callSite instanceof ConstantCallSite) {
 313             appendixResult[0] = callSite.dynamicInvoker();
 314             return Invokers.linkToTargetMethod(type);
 315         } else {
 316             appendixResult[0] = callSite;
 317             return Invokers.linkToCallSiteMethod(type);
 318         }
 319     }
 320     // Tracing logic:
 321     static MemberName linkCallSiteTracing(Class<?> caller,
 322                                           MethodHandle bootstrapMethod,
 323                                           String name, MethodType type,
 324                                           Object staticArguments,
 325                                           Object[] appendixResult) {
 326         Object bsmReference = bootstrapMethod.internalMemberName();
 327         if (bsmReference == null)  bsmReference = bootstrapMethod;
 328         Object staticArglist = (staticArguments instanceof Object[] ?
 329                                 java.util.Arrays.asList((Object[]) staticArguments) :
 330                                 staticArguments);
 331         System.out.println("linkCallSite "+caller.getName()+" "+
 332                            bsmReference+" "+
 333                            name+type+"/"+staticArglist);
 334         try {
 335             MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type,
 336                                               staticArguments, appendixResult);
 337             System.out.println("linkCallSite => "+res+" + "+appendixResult[0]);
 338             return res;
 339         } catch (Throwable ex) {
 340             System.out.println("linkCallSite => throw "+ex);
 341             throw ex;
 342         }
 343     }
 344 
 345     /**
 346      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 347      */
 348     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 349         return MethodType.makeImpl(rtype, ptypes, true);
 350     }
 351 
 352     /**
 353      * The JVM wants to link a call site that requires a dynamic type check.
 354      * Name is a type-checking invoker, invokeExact or invoke.
 355      * Return a JVM method (MemberName) to handle the invoking.
 356      * The method assumes the following arguments on the stack:
 357      * 0: the method handle being invoked
 358      * 1-N: the arguments to the method handle invocation
 359      * N+1: an optional, implicitly added argument (typically the given MethodType)
 360      * <p>
 361      * The nominal method at such a call site is an instance of
 362      * a signature-polymorphic method (see @PolymorphicSignature).
 363      * Such method instances are user-visible entities which are
 364      * "split" from the generic placeholder method in {@code MethodHandle}.
 365      * (Note that the placeholder method is not identical with any of
 366      * its instances.  If invoked reflectively, is guaranteed to throw an
 367      * {@code UnsupportedOperationException}.)
 368      * If the signature-polymorphic method instance is ever reified,
 369      * it appears as a "copy" of the original placeholder
 370      * (a native final member of {@code MethodHandle}) except
 371      * that its type descriptor has shape required by the instance,
 372      * and the method instance is <em>not</em> varargs.
 373      * The method instance is also marked synthetic, since the
 374      * method (by definition) does not appear in Java source code.
 375      * <p>
 376      * The JVM is allowed to reify this method as instance metadata.
 377      * For example, {@code invokeBasic} is always reified.
 378      * But the JVM may instead call {@code linkMethod}.
 379      * If the result is an * ordered pair of a {@code (method, appendix)},
 380      * the method gets all the arguments (0..N inclusive)
 381      * plus the appendix (N+1), and uses the appendix to complete the call.
 382      * In this way, one reusable method (called a "linker method")
 383      * can perform the function of any number of polymorphic instance
 384      * methods.
 385      * <p>
 386      * Linker methods are allowed to be weakly typed, with any or
 387      * all references rewritten to {@code Object} and any primitives
 388      * (except {@code long}/{@code float}/{@code double})
 389      * rewritten to {@code int}.
 390      * A linker method is trusted to return a strongly typed result,
 391      * according to the specific method type descriptor of the
 392      * signature-polymorphic instance it is emulating.
 393      * This can involve (as necessary) a dynamic check using
 394      * data extracted from the appendix argument.
 395      * <p>
 396      * The JVM does not inspect the appendix, other than to pass
 397      * it verbatim to the linker method at every call.
 398      * This means that the JDK runtime has wide latitude
 399      * for choosing the shape of each linker method and its
 400      * corresponding appendix.
 401      * Linker methods should be generated from {@code LambdaForm}s
 402      * so that they do not become visible on stack traces.
 403      * <p>
 404      * The {@code linkMethod} call is free to omit the appendix
 405      * (returning null) and instead emulate the required function
 406      * completely in the linker method.
 407      * As a corner case, if N==255, no appendix is possible.
 408      * In this case, the method returned must be custom-generated to
 409      * to perform any needed type checking.
 410      * <p>
 411      * If the JVM does not reify a method at a call site, but instead
 412      * calls {@code linkMethod}, the corresponding call represented
 413      * in the bytecodes may mention a valid method which is not
 414      * representable with a {@code MemberName}.
 415      * Therefore, use cases for {@code linkMethod} tend to correspond to
 416      * special cases in reflective code such as {@code findVirtual}
 417      * or {@code revealDirect}.
 418      */
 419     static MemberName linkMethod(Class<?> callerClass, int refKind,
 420                                  Class<?> defc, String name, Object type,
 421                                  Object[] appendixResult) {
 422         if (!TRACE_METHOD_LINKAGE)
 423             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 424         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
 425     }
 426     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
 427                                      Class<?> defc, String name, Object type,
 428                                      Object[] appendixResult) {
 429         try {
 430             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
 431                 return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
 432             }
 433         } catch (Throwable ex) {
 434             if (ex instanceof LinkageError)
 435                 throw (LinkageError) ex;
 436             else
 437                 throw new LinkageError(ex.getMessage(), ex);
 438         }
 439         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
 440     }
 441     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
 442         if (type instanceof MethodType)
 443             return (MethodType) type;
 444         else
 445             return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
 446     }
 447     // Tracing logic:
 448     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
 449                                         Class<?> defc, String name, Object type,
 450                                         Object[] appendixResult) {
 451         System.out.println("linkMethod "+defc.getName()+"."+
 452                            name+type+"/"+Integer.toHexString(refKind));
 453         try {
 454             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 455             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
 456             return res;
 457         } catch (Throwable ex) {
 458             System.out.println("linkMethod => throw "+ex);
 459             throw ex;
 460         }
 461     }
 462 
 463 
 464     /**
 465      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 466      * It will make an up-call to this method.  (Do not change the name or signature.)
 467      * The type argument is a Class for field requests and a MethodType for non-fields.
 468      * <p>
 469      * Recent versions of the JVM may also pass a resolved MemberName for the type.
 470      * In that case, the name is ignored and may be null.
 471      */
 472     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 473                                                  Class<?> defc, String name, Object type) {
 474         try {
 475             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 476             assert(refKindIsValid(refKind));
 477             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
 478         } catch (IllegalAccessException ex) {
 479             Throwable cause = ex.getCause();
 480             if (cause instanceof AbstractMethodError) {
 481                 throw (AbstractMethodError) cause;
 482             } else {
 483                 Error err = new IllegalAccessError(ex.getMessage());
 484                 throw initCauseFrom(err, ex);
 485             }
 486         } catch (NoSuchMethodException ex) {
 487             Error err = new NoSuchMethodError(ex.getMessage());
 488             throw initCauseFrom(err, ex);
 489         } catch (NoSuchFieldException ex) {
 490             Error err = new NoSuchFieldError(ex.getMessage());
 491             throw initCauseFrom(err, ex);
 492         } catch (ReflectiveOperationException ex) {
 493             Error err = new IncompatibleClassChangeError();
 494             throw initCauseFrom(err, ex);
 495         }
 496     }
 497 
 498     /**
 499      * Use best possible cause for err.initCause(), substituting the
 500      * cause for err itself if the cause has the same (or better) type.
 501      */
 502     static private Error initCauseFrom(Error err, Exception ex) {
 503         Throwable th = ex.getCause();
 504         if (err.getClass().isInstance(th))
 505            return (Error) th;
 506         err.initCause(th == null ? ex : th);
 507         return err;
 508     }
 509 
 510     /**
 511      * Is this method a caller-sensitive method?
 512      * I.e., does it call Reflection.getCallerClass or a similar method
 513      * to ask about the identity of its caller?
 514      */
 515     static boolean isCallerSensitive(MemberName mem) {
 516         if (!mem.isInvocable())  return false;  // fields are not caller sensitive
 517 
 518         return mem.isCallerSensitive() || canBeCalledVirtual(mem);
 519     }
 520 
 521     static boolean canBeCalledVirtual(MemberName mem) {
 522         assert(mem.isInvocable());
 523         Class<?> defc = mem.getDeclaringClass();
 524         switch (mem.getName()) {
 525         case "checkMemberAccess":
 526             return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
 527         case "getContextClassLoader":
 528             return canBeCalledVirtual(mem, java.lang.Thread.class);
 529         }
 530         return false;
 531     }
 532 
 533     static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
 534         Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
 535         if (symbolicRefClass == definingClass)  return true;
 536         if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
 537         return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
 538                 symbolicRefClass.isInterface());                     // Mdef implements Msym
 539     }
 540 }
--- EOF ---