1 /*
   2  * Copyright (c) 2008, 2015, 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 import jdk.internal.ref.CleanerFactory;
  34 
  35 /**
  36  * The JVM interface for the method handles package is all here.
  37  * This is an interface internal and private to an implementation 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 jdk.internal.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     /// CallSite support
  60 
  61     /** Tell the JVM that we need to change the target of a CallSite. */
  62     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
  63     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
  64 
  65     /** Represents a context to track nmethod dependencies on CallSite instance target. */
  66     static class CallSiteContext implements Runnable {
  67         //@Injected JVM_nmethodBucket* vmdependencies;
  68 
  69         static CallSiteContext make(CallSite cs) {
  70             final CallSiteContext newContext = new CallSiteContext();
  71             // CallSite instance is tracked by a Cleanable which clears native
  72             // structures allocated for CallSite context. Though the CallSite can
  73             // become unreachable, its Context is retained by the Cleanable instance
  74             // (which is referenced from Cleaner instance which is referenced from
  75             // CleanerFactory class) until cleanup is performed.
  76             CleanerFactory.cleaner().register(cs, newContext);
  77             return newContext;
  78         }
  79 
  80         @Override
  81         public void run() {
  82             MethodHandleNatives.clearCallSiteContext(this);
  83         }
  84     }
  85 
  86     /** Invalidate all recorded nmethods. */
  87     private static native void clearCallSiteContext(CallSiteContext context);
  88 
  89     private static native void registerNatives();
  90     static {
  91         registerNatives();
  92     }
  93 
  94     /**
  95      * Compile-time constants go here. This collection exists not only for
  96      * reference from clients, but also for ensuring the VM and JDK agree on the
  97      * values of these constants (see {@link #verifyConstants()}).
  98      */
  99     static class Constants {
 100         Constants() { } // static only
 101 
 102         static final int
 103             MN_IS_METHOD           = 0x00010000, // method (not constructor)
 104             MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
 105             MN_IS_FIELD            = 0x00040000, // field
 106             MN_IS_TYPE             = 0x00080000, // nested type
 107             MN_CALLER_SENSITIVE    = 0x00100000, // @CallerSensitive annotation detected
 108             MN_REFERENCE_KIND_SHIFT = 24, // refKind
 109             MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
 110             // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
 111             MN_SEARCH_SUPERCLASSES = 0x00100000,
 112             MN_SEARCH_INTERFACES   = 0x00200000;
 113 
 114         /**
 115          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
 116          */
 117         static final byte
 118             REF_NONE                    = 0,  // null value
 119             REF_getField                = 1,
 120             REF_getStatic               = 2,
 121             REF_putField                = 3,
 122             REF_putStatic               = 4,
 123             REF_invokeVirtual           = 5,
 124             REF_invokeStatic            = 6,
 125             REF_invokeSpecial           = 7,
 126             REF_newInvokeSpecial        = 8,
 127             REF_invokeInterface         = 9,
 128             REF_LIMIT                  = 10;
 129     }
 130 
 131     static boolean refKindIsValid(int refKind) {
 132         return (refKind > REF_NONE && refKind < REF_LIMIT);
 133     }
 134     static boolean refKindIsField(byte refKind) {
 135         assert(refKindIsValid(refKind));
 136         return (refKind <= REF_putStatic);
 137     }
 138     static boolean refKindIsGetter(byte refKind) {
 139         assert(refKindIsValid(refKind));
 140         return (refKind <= REF_getStatic);
 141     }
 142     static boolean refKindIsSetter(byte refKind) {
 143         return refKindIsField(refKind) && !refKindIsGetter(refKind);
 144     }
 145     static boolean refKindIsMethod(byte refKind) {
 146         return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
 147     }
 148     static boolean refKindIsConstructor(byte refKind) {
 149         return (refKind == REF_newInvokeSpecial);
 150     }
 151     static boolean refKindHasReceiver(byte refKind) {
 152         assert(refKindIsValid(refKind));
 153         return (refKind & 1) != 0;
 154     }
 155     static boolean refKindIsStatic(byte refKind) {
 156         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
 157     }
 158     static boolean refKindDoesDispatch(byte refKind) {
 159         assert(refKindIsValid(refKind));
 160         return (refKind == REF_invokeVirtual ||
 161                 refKind == REF_invokeInterface);
 162     }
 163     static {
 164         final int HR_MASK = ((1 << REF_getField) |
 165                              (1 << REF_putField) |
 166                              (1 << REF_invokeVirtual) |
 167                              (1 << REF_invokeSpecial) |
 168                              (1 << REF_invokeInterface)
 169                             );
 170         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
 171             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
 172         }
 173     }
 174     static String refKindName(byte refKind) {
 175         assert(refKindIsValid(refKind));
 176         switch (refKind) {
 177         case REF_getField:          return "getField";
 178         case REF_getStatic:         return "getStatic";
 179         case REF_putField:          return "putField";
 180         case REF_putStatic:         return "putStatic";
 181         case REF_invokeVirtual:     return "invokeVirtual";
 182         case REF_invokeStatic:      return "invokeStatic";
 183         case REF_invokeSpecial:     return "invokeSpecial";
 184         case REF_newInvokeSpecial:  return "newInvokeSpecial";
 185         case REF_invokeInterface:   return "invokeInterface";
 186         default:                    return "REF_???";
 187         }
 188     }
 189 
 190     private static native int getNamedCon(int which, Object[] name);
 191     static boolean verifyConstants() {
 192         Object[] box = { null };
 193         for (int i = 0; ; i++) {
 194             box[0] = null;
 195             int vmval = getNamedCon(i, box);
 196             if (box[0] == null)  break;
 197             String name = (String) box[0];
 198             try {
 199                 Field con = Constants.class.getDeclaredField(name);
 200                 int jval = con.getInt(null);
 201                 if (jval == vmval)  continue;
 202                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 203                 if (name.equals("CONV_OP_LIMIT")) {
 204                     System.err.println("warning: "+err);
 205                     continue;
 206                 }
 207                 throw new InternalError(err);
 208             } catch (NoSuchFieldException | IllegalAccessException ex) {
 209                 String err = (name+": JVM has "+vmval+" which Java does not define");
 210                 // ignore exotic ops the JVM cares about; we just wont issue them
 211                 //System.err.println("warning: "+err);
 212                 continue;
 213             }
 214         }
 215         return true;
 216     }
 217     static {
 218         assert(verifyConstants());
 219     }
 220 
 221     // Up-calls from the JVM.
 222     // These must NOT be public.
 223 
 224     /**
 225      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 226      */
 227     static MemberName linkCallSite(Object callerObj,
 228                                    Object bootstrapMethodObj,
 229                                    Object nameObj, Object typeObj,
 230                                    Object staticArguments,
 231                                    Object[] appendixResult) {
 232         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 233         Class<?> caller = (Class<?>)callerObj;
 234         String name = nameObj.toString().intern();
 235         MethodType type = (MethodType)typeObj;
 236         if (!TRACE_METHOD_LINKAGE)
 237             return linkCallSiteImpl(caller, bootstrapMethod, name, type,
 238                                     staticArguments, appendixResult);
 239         return linkCallSiteTracing(caller, bootstrapMethod, name, type,
 240                                    staticArguments, appendixResult);
 241     }
 242     static MemberName linkCallSiteImpl(Class<?> caller,
 243                                        MethodHandle bootstrapMethod,
 244                                        String name, MethodType type,
 245                                        Object staticArguments,
 246                                        Object[] appendixResult) {
 247         CallSite callSite = CallSite.makeSite(bootstrapMethod,
 248                                               name,
 249                                               type,
 250                                               staticArguments,
 251                                               caller);
 252         if (callSite instanceof ConstantCallSite) {
 253             appendixResult[0] = callSite.dynamicInvoker();
 254             return Invokers.linkToTargetMethod(type);
 255         } else {
 256             appendixResult[0] = callSite;
 257             return Invokers.linkToCallSiteMethod(type);
 258         }
 259     }
 260     // Tracing logic:
 261     static MemberName linkCallSiteTracing(Class<?> caller,
 262                                           MethodHandle bootstrapMethod,
 263                                           String name, MethodType type,
 264                                           Object staticArguments,
 265                                           Object[] appendixResult) {
 266         Object bsmReference = bootstrapMethod.internalMemberName();
 267         if (bsmReference == null)  bsmReference = bootstrapMethod;
 268         Object staticArglist = (staticArguments instanceof Object[] ?
 269                                 java.util.Arrays.asList((Object[]) staticArguments) :
 270                                 staticArguments);
 271         System.out.println("linkCallSite "+caller.getName()+" "+
 272                            bsmReference+" "+
 273                            name+type+"/"+staticArglist);
 274         try {
 275             MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type,
 276                                               staticArguments, appendixResult);
 277             System.out.println("linkCallSite => "+res+" + "+appendixResult[0]);
 278             return res;
 279         } catch (Throwable ex) {
 280             System.out.println("linkCallSite => throw "+ex);
 281             throw ex;
 282         }
 283     }
 284 
 285     /**
 286      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 287      */
 288     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 289         return MethodType.makeImpl(rtype, ptypes, true);
 290     }
 291 
 292     /**
 293      * The JVM wants to link a call site that requires a dynamic type check.
 294      * Name is a type-checking invoker, invokeExact or invoke.
 295      * Return a JVM method (MemberName) to handle the invoking.
 296      * The method assumes the following arguments on the stack:
 297      * 0: the method handle being invoked
 298      * 1-N: the arguments to the method handle invocation
 299      * N+1: an optional, implicitly added argument (typically the given MethodType)
 300      * <p>
 301      * The nominal method at such a call site is an instance of
 302      * a signature-polymorphic method (see @PolymorphicSignature).
 303      * Such method instances are user-visible entities which are
 304      * "split" from the generic placeholder method in {@code MethodHandle}.
 305      * (Note that the placeholder method is not identical with any of
 306      * its instances.  If invoked reflectively, is guaranteed to throw an
 307      * {@code UnsupportedOperationException}.)
 308      * If the signature-polymorphic method instance is ever reified,
 309      * it appears as a "copy" of the original placeholder
 310      * (a native final member of {@code MethodHandle}) except
 311      * that its type descriptor has shape required by the instance,
 312      * and the method instance is <em>not</em> varargs.
 313      * The method instance is also marked synthetic, since the
 314      * method (by definition) does not appear in Java source code.
 315      * <p>
 316      * The JVM is allowed to reify this method as instance metadata.
 317      * For example, {@code invokeBasic} is always reified.
 318      * But the JVM may instead call {@code linkMethod}.
 319      * If the result is an * ordered pair of a {@code (method, appendix)},
 320      * the method gets all the arguments (0..N inclusive)
 321      * plus the appendix (N+1), and uses the appendix to complete the call.
 322      * In this way, one reusable method (called a "linker method")
 323      * can perform the function of any number of polymorphic instance
 324      * methods.
 325      * <p>
 326      * Linker methods are allowed to be weakly typed, with any or
 327      * all references rewritten to {@code Object} and any primitives
 328      * (except {@code long}/{@code float}/{@code double})
 329      * rewritten to {@code int}.
 330      * A linker method is trusted to return a strongly typed result,
 331      * according to the specific method type descriptor of the
 332      * signature-polymorphic instance it is emulating.
 333      * This can involve (as necessary) a dynamic check using
 334      * data extracted from the appendix argument.
 335      * <p>
 336      * The JVM does not inspect the appendix, other than to pass
 337      * it verbatim to the linker method at every call.
 338      * This means that the JDK runtime has wide latitude
 339      * for choosing the shape of each linker method and its
 340      * corresponding appendix.
 341      * Linker methods should be generated from {@code LambdaForm}s
 342      * so that they do not become visible on stack traces.
 343      * <p>
 344      * The {@code linkMethod} call is free to omit the appendix
 345      * (returning null) and instead emulate the required function
 346      * completely in the linker method.
 347      * As a corner case, if N==255, no appendix is possible.
 348      * In this case, the method returned must be custom-generated to
 349      * to perform any needed type checking.
 350      * <p>
 351      * If the JVM does not reify a method at a call site, but instead
 352      * calls {@code linkMethod}, the corresponding call represented
 353      * in the bytecodes may mention a valid method which is not
 354      * representable with a {@code MemberName}.
 355      * Therefore, use cases for {@code linkMethod} tend to correspond to
 356      * special cases in reflective code such as {@code findVirtual}
 357      * or {@code revealDirect}.
 358      */
 359     static MemberName linkMethod(Class<?> callerClass, int refKind,
 360                                  Class<?> defc, String name, Object type,
 361                                  Object[] appendixResult) {
 362         if (!TRACE_METHOD_LINKAGE)
 363             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 364         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
 365     }
 366     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
 367                                      Class<?> defc, String name, Object type,
 368                                      Object[] appendixResult) {
 369         try {
 370             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
 371                 return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
 372             }
 373         } catch (Throwable ex) {
 374             if (ex instanceof LinkageError)
 375                 throw (LinkageError) ex;
 376             else
 377                 throw new LinkageError(ex.getMessage(), ex);
 378         }
 379         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
 380     }
 381     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
 382         if (type instanceof MethodType)
 383             return (MethodType) type;
 384         else
 385             return MethodType.fromDescriptor((String)type, callerClass.getClassLoader());
 386     }
 387     // Tracing logic:
 388     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
 389                                         Class<?> defc, String name, Object type,
 390                                         Object[] appendixResult) {
 391         System.out.println("linkMethod "+defc.getName()+"."+
 392                            name+type+"/"+Integer.toHexString(refKind));
 393         try {
 394             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 395             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
 396             return res;
 397         } catch (Throwable ex) {
 398             System.out.println("linkMethod => throw "+ex);
 399             throw ex;
 400         }
 401     }
 402 
 403 
 404     /**
 405      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 406      * It will make an up-call to this method.  (Do not change the name or signature.)
 407      * The type argument is a Class for field requests and a MethodType for non-fields.
 408      * <p>
 409      * Recent versions of the JVM may also pass a resolved MemberName for the type.
 410      * In that case, the name is ignored and may be null.
 411      */
 412     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 413                                                  Class<?> defc, String name, Object type) {
 414         try {
 415             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 416             assert(refKindIsValid(refKind));
 417             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
 418         } catch (IllegalAccessException ex) {
 419             Throwable cause = ex.getCause();
 420             if (cause instanceof AbstractMethodError) {
 421                 throw (AbstractMethodError) cause;
 422             } else {
 423                 Error err = new IllegalAccessError(ex.getMessage());
 424                 throw initCauseFrom(err, ex);
 425             }
 426         } catch (NoSuchMethodException ex) {
 427             Error err = new NoSuchMethodError(ex.getMessage());
 428             throw initCauseFrom(err, ex);
 429         } catch (NoSuchFieldException ex) {
 430             Error err = new NoSuchFieldError(ex.getMessage());
 431             throw initCauseFrom(err, ex);
 432         } catch (ReflectiveOperationException ex) {
 433             Error err = new IncompatibleClassChangeError();
 434             throw initCauseFrom(err, ex);
 435         }
 436     }
 437 
 438     /**
 439      * Use best possible cause for err.initCause(), substituting the
 440      * cause for err itself if the cause has the same (or better) type.
 441      */
 442     private static Error initCauseFrom(Error err, Exception ex) {
 443         Throwable th = ex.getCause();
 444         if (err.getClass().isInstance(th))
 445            return (Error) th;
 446         err.initCause(th == null ? ex : th);
 447         return err;
 448     }
 449 
 450     /**
 451      * Is this method a caller-sensitive method?
 452      * I.e., does it call Reflection.getCallerClass or a similar method
 453      * to ask about the identity of its caller?
 454      */
 455     static boolean isCallerSensitive(MemberName mem) {
 456         if (!mem.isInvocable())  return false;  // fields are not caller sensitive
 457 
 458         return mem.isCallerSensitive() || canBeCalledVirtual(mem);
 459     }
 460 
 461     static boolean canBeCalledVirtual(MemberName mem) {
 462         assert(mem.isInvocable());
 463         Class<?> defc = mem.getDeclaringClass();
 464         switch (mem.getName()) {
 465         case "checkMemberAccess":
 466             return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
 467         case "getContextClassLoader":
 468             return canBeCalledVirtual(mem, java.lang.Thread.class);
 469         }
 470         return false;
 471     }
 472 
 473     static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
 474         Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
 475         if (symbolicRefClass == definingClass)  return true;
 476         if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
 477         return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
 478                 symbolicRefClass.isInterface());                     // Mdef implements Msym
 479     }
 480 }