1 /*
   2  * Copyright (c) 2008, 2016, 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 static java.lang.invoke.MethodHandleStatics.*;
  29 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  30 
  31 import jdk.internal.vm.annotation.Stable;
  32 
  33 /**
  34  * A {@code CallSite} is a holder for a variable {@link MethodHandle},
  35  * which is called its {@code target}.
  36  * An {@code invokedynamic} instruction linked to a {@code CallSite} delegates
  37  * all calls to the site's current target.
  38  * A {@code CallSite} may be associated with several {@code invokedynamic}
  39  * instructions, or it may be "free floating", associated with none.
  40  * In any case, it may be invoked through an associated method handle
  41  * called its {@linkplain #dynamicInvoker dynamic invoker}.
  42  * <p>
  43  * {@code CallSite} is an abstract class which does not allow
  44  * direct subclassing by users.  It has three immediate,
  45  * concrete subclasses that may be either instantiated or subclassed.
  46  * <ul>
  47  * <li>If a mutable target is not required, an {@code invokedynamic} instruction
  48  * may be permanently bound by means of a {@linkplain ConstantCallSite constant call site}.
  49  * <li>If a mutable target is required which has volatile variable semantics,
  50  * because updates to the target must be immediately and reliably witnessed by other threads,
  51  * a {@linkplain VolatileCallSite volatile call site} may be used.
  52  * <li>Otherwise, if a mutable target is required,
  53  * a {@linkplain MutableCallSite mutable call site} may be used.
  54  * </ul>
  55  * <p>
  56  * A non-constant call site may be <em>relinked</em> by changing its target.
  57  * The new target must have the same {@linkplain MethodHandle#type() type}
  58  * as the previous target.
  59  * Thus, though a call site can be relinked to a series of
  60  * successive targets, it cannot change its type.
  61  * <p>
  62  * Here is a sample use of call sites and bootstrap methods which links every
  63  * dynamic call site to print its arguments:
  64 <blockquote><pre>{@code
  65 static void test() throws Throwable {
  66     // THE FOLLOWING LINE IS PSEUDOCODE FOR A JVM INSTRUCTION
  67     InvokeDynamic[#bootstrapDynamic].baz("baz arg", 2, 3.14);
  68 }
  69 private static void printArgs(Object... args) {
  70   System.out.println(java.util.Arrays.deepToString(args));
  71 }
  72 private static final MethodHandle printArgs;
  73 static {
  74   MethodHandles.Lookup lookup = MethodHandles.lookup();
  75   Class thisClass = lookup.lookupClass();  // (who am I?)
  76   printArgs = lookup.findStatic(thisClass,
  77       "printArgs", MethodType.methodType(void.class, Object[].class));
  78 }
  79 private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String name, MethodType type) {
  80   // ignore caller and name, but match the type:
  81   return new ConstantCallSite(printArgs.asType(type));
  82 }
  83 }</pre></blockquote>
  84  * @author John Rose, JSR 292 EG
  85  */
  86 abstract
  87 public class CallSite {
  88 
  89     // The actual payload of this call site:
  90     /*package-private*/
  91     MethodHandle target;    // Note: This field is known to the JVM.  Do not change.
  92 
  93     /**
  94      * Make a blank call site object with the given method type.
  95      * An initial target method is supplied which will throw
  96      * an {@link IllegalStateException} if called.
  97      * <p>
  98      * Before this {@code CallSite} object is returned from a bootstrap method,
  99      * it is usually provided with a more useful target method,
 100      * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
 101      * @throws NullPointerException if the proposed type is null
 102      */
 103     /*package-private*/
 104     CallSite(MethodType type) {
 105         target = makeUninitializedCallSite(type);
 106     }
 107 
 108     /**
 109      * Make a call site object equipped with an initial target method handle.
 110      * @param target the method handle which will be the initial target of the call site
 111      * @throws NullPointerException if the proposed target is null
 112      */
 113     /*package-private*/
 114     CallSite(MethodHandle target) {
 115         target.type();  // null check
 116         this.target = target;
 117     }
 118 
 119     /**
 120      * Make a call site object equipped with an initial target method handle.
 121      * @param targetType the desired type of the call site
 122      * @param createTargetHook a hook which will bind the call site to the target method handle
 123      * @throws WrongMethodTypeException if the hook cannot be invoked on the required arguments,
 124      *         or if the target returned by the hook is not of the given {@code targetType}
 125      * @throws NullPointerException if the hook returns a null value
 126      * @throws ClassCastException if the hook returns something other than a {@code MethodHandle}
 127      * @throws Throwable anything else thrown by the hook function
 128      */
 129     /*package-private*/
 130     CallSite(MethodType targetType, MethodHandle createTargetHook) throws Throwable {
 131         this(targetType);
 132         ConstantCallSite selfCCS = (ConstantCallSite) this;
 133         MethodHandle boundTarget = (MethodHandle) createTargetHook.invokeWithArguments(selfCCS);
 134         checkTargetChange(this.target, boundTarget);
 135         this.target = boundTarget;
 136     }
 137 
 138     /**
 139      * {@code CallSite} dependency context.
 140      * JVM uses CallSite.context to store nmethod dependencies on the call site target.
 141      */
 142     private final MethodHandleNatives.CallSiteContext context = MethodHandleNatives.CallSiteContext.make(this);
 143 
 144     /**
 145      * Returns the type of this call site's target.
 146      * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
 147      * The {@code setTarget} method enforces this invariant by refusing any new target that does
 148      * not have the previous target's type.
 149      * @return the type of the current target, which is also the type of any future target
 150      */
 151     public MethodType type() {
 152         // warning:  do not call getTarget here, because CCS.getTarget can throw IllegalStateException
 153         return target.type();
 154     }
 155 
 156     /**
 157      * Returns the target method of the call site, according to the
 158      * behavior defined by this call site's specific class.
 159      * The immediate subclasses of {@code CallSite} document the
 160      * class-specific behaviors of this method.
 161      *
 162      * @return the current linkage state of the call site, its target method handle
 163      * @see ConstantCallSite
 164      * @see VolatileCallSite
 165      * @see #setTarget
 166      * @see ConstantCallSite#getTarget
 167      * @see MutableCallSite#getTarget
 168      * @see VolatileCallSite#getTarget
 169      */
 170     public abstract MethodHandle getTarget();
 171 
 172     /**
 173      * Updates the target method of this call site, according to the
 174      * behavior defined by this call site's specific class.
 175      * The immediate subclasses of {@code CallSite} document the
 176      * class-specific behaviors of this method.
 177      * <p>
 178      * The type of the new target must be {@linkplain MethodType#equals equal to}
 179      * the type of the old target.
 180      *
 181      * @param newTarget the new target
 182      * @throws NullPointerException if the proposed new target is null
 183      * @throws WrongMethodTypeException if the proposed new target
 184      *         has a method type that differs from the previous target
 185      * @see CallSite#getTarget
 186      * @see ConstantCallSite#setTarget
 187      * @see MutableCallSite#setTarget
 188      * @see VolatileCallSite#setTarget
 189      */
 190     public abstract void setTarget(MethodHandle newTarget);
 191 
 192     void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
 193         MethodType oldType = oldTarget.type();
 194         MethodType newType = newTarget.type();  // null check!
 195         if (!newType.equals(oldType))
 196             throw wrongTargetType(newTarget, oldType);
 197     }
 198 
 199     private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
 200         return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
 201     }
 202 
 203     /**
 204      * Produces a method handle equivalent to an invokedynamic instruction
 205      * which has been linked to this call site.
 206      * <p>
 207      * This method is equivalent to the following code:
 208      * <blockquote><pre>{@code
 209      * MethodHandle getTarget, invoker, result;
 210      * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
 211      * invoker = MethodHandles.exactInvoker(this.type());
 212      * result = MethodHandles.foldArguments(invoker, getTarget)
 213      * }</pre></blockquote>
 214      *
 215      * @return a method handle which always invokes this call site's current target
 216      */
 217     public abstract MethodHandle dynamicInvoker();
 218 
 219     /*non-public*/ MethodHandle makeDynamicInvoker() {
 220         MethodHandle getTarget = getTargetHandle().bindArgumentL(0, this);
 221         MethodHandle invoker = MethodHandles.exactInvoker(this.type());
 222         return MethodHandles.foldArguments(invoker, getTarget);
 223     }
 224 
 225     private static @Stable MethodHandle GET_TARGET;
 226     private static MethodHandle getTargetHandle() {
 227         MethodHandle handle = GET_TARGET;
 228         if (handle != null) {
 229             return handle;
 230         }
 231         try {
 232             return GET_TARGET = IMPL_LOOKUP.
 233                     findVirtual(CallSite.class, "getTarget",
 234                                 MethodType.methodType(MethodHandle.class));
 235         } catch (ReflectiveOperationException e) {
 236             throw newInternalError(e);
 237         }
 238     }
 239 
 240     private static @Stable MethodHandle THROW_UCS;
 241     private static MethodHandle uninitializedCallSiteHandle() {
 242         MethodHandle handle = THROW_UCS;
 243         if (handle != null) {
 244             return handle;
 245         }
 246         try {
 247             return THROW_UCS = IMPL_LOOKUP.
 248                 findStatic(CallSite.class, "uninitializedCallSite",
 249                            MethodType.methodType(Object.class, Object[].class));
 250         } catch (ReflectiveOperationException e) {
 251             throw newInternalError(e);
 252         }
 253     }
 254 
 255     /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
 256     private static Object uninitializedCallSite(Object... ignore) {
 257         throw new IllegalStateException("uninitialized call site");
 258     }
 259 
 260     private MethodHandle makeUninitializedCallSite(MethodType targetType) {
 261         MethodType basicType = targetType.basicType();
 262         MethodHandle invoker = basicType.form().cachedMethodHandle(MethodTypeForm.MH_UNINIT_CS);
 263         if (invoker == null) {
 264             invoker = uninitializedCallSiteHandle().asType(basicType);
 265             invoker = basicType.form().setCachedMethodHandle(MethodTypeForm.MH_UNINIT_CS, invoker);
 266         }
 267         // unchecked view is OK since no values will be received or returned
 268         return invoker.viewAsType(targetType, false);
 269     }
 270 
 271     // unsafe stuff:
 272     private static @Stable long TARGET_OFFSET;
 273     private static long getTargetOffset() {
 274         long offset = TARGET_OFFSET;
 275         if (offset > 0) {
 276             return offset;
 277         }
 278         try {
 279             offset = TARGET_OFFSET = UNSAFE.objectFieldOffset(CallSite.class.getDeclaredField("target"));
 280             assert(offset > 0);
 281             return offset;
 282         } catch (Exception ex) { throw newInternalError(ex); }
 283     }
 284 
 285     /*package-private*/
 286     void setTargetNormal(MethodHandle newTarget) {
 287         MethodHandleNatives.setCallSiteTargetNormal(this, newTarget);
 288     }
 289     /*package-private*/
 290     MethodHandle getTargetVolatile() {
 291         return (MethodHandle) UNSAFE.getObjectVolatile(this, getTargetOffset());
 292     }
 293     /*package-private*/
 294     void setTargetVolatile(MethodHandle newTarget) {
 295         MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget);
 296     }
 297 
 298     // this implements the upcall from the JVM, MethodHandleNatives.linkCallSite:
 299     static CallSite makeSite(MethodHandle bootstrapMethod,
 300                              // Callee information:
 301                              String name, MethodType type,
 302                              // Extra arguments for BSM, if any:
 303                              Object info,
 304                              // Caller information:
 305                              Class<?> callerClass) {
 306         MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass);
 307         CallSite site;
 308         try {
 309             Object binding;
 310             info = maybeReBox(info);
 311             if (info == null) {
 312                 binding = bootstrapMethod.invoke(caller, name, type);
 313             } else if (!info.getClass().isArray()) {
 314                 binding = bootstrapMethod.invoke(caller, name, type, info);
 315             } else {
 316                 Object[] argv = (Object[]) info;
 317                 maybeReBoxElements(argv);
 318                 switch (argv.length) {
 319                     case 0:
 320                         binding = bootstrapMethod.invoke(caller, name, type);
 321                         break;
 322                     case 1:
 323                         binding = bootstrapMethod.invoke(caller, name, type,
 324                                                          argv[0]);
 325                         break;
 326                     case 2:
 327                         binding = bootstrapMethod.invoke(caller, name, type,
 328                                                          argv[0], argv[1]);
 329                         break;
 330                     case 3:
 331                         binding = bootstrapMethod.invoke(caller, name, type,
 332                                                          argv[0], argv[1], argv[2]);
 333                         break;
 334                     case 4:
 335                         binding = bootstrapMethod.invoke(caller, name, type,
 336                                                          argv[0], argv[1], argv[2], argv[3]);
 337                         break;
 338                     case 5:
 339                         binding = bootstrapMethod.invoke(caller, name, type,
 340                                                          argv[0], argv[1], argv[2], argv[3], argv[4]);
 341                         break;
 342                     case 6:
 343                         binding = bootstrapMethod.invoke(caller, name, type,
 344                                                          argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
 345                         break;
 346                     default:
 347                         final int NON_SPREAD_ARG_COUNT = 3;  // (caller, name, type)
 348                         if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY)
 349                             throw new BootstrapMethodError("too many bootstrap method arguments");
 350 
 351                         MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length);
 352                         MethodHandle typedBSM = bootstrapMethod.asType(invocationType);
 353                         MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT);
 354                         binding = spreader.invokeExact(typedBSM, (Object) caller, (Object) name, (Object) type, argv);
 355                 }
 356             }
 357             if (binding instanceof CallSite) {
 358                 site = (CallSite) binding;
 359             } else {
 360                 // See the "Linking Exceptions" section for the invokedynamic
 361                 // instruction in JVMS 6.5.
 362                 // Throws a runtime exception defining the cause that is then
 363                 // in the "catch (Throwable ex)" a few lines below wrapped in
 364                 // BootstrapMethodError
 365                 throw new ClassCastException("bootstrap method failed to produce a CallSite");
 366             }
 367             if (!site.getTarget().type().equals(type)) {
 368                 // See the "Linking Exceptions" section for the invokedynamic
 369                 // instruction in JVMS 6.5.
 370                 // Throws a runtime exception defining the cause that is then
 371                 // in the "catch (Throwable ex)" a few lines below wrapped in
 372                 // BootstrapMethodError
 373                 throw wrongTargetType(site.getTarget(), type);
 374             }
 375         } catch (Error e) {
 376             // Pass through an Error, including BootstrapMethodError, any other
 377             // form of linkage error, such as IllegalAccessError if the bootstrap
 378             // method is inaccessible, or say ThreadDeath/OutOfMemoryError
 379             // See the "Linking Exceptions" section for the invokedynamic
 380             // instruction in JVMS 6.5.
 381             throw e;
 382         } catch (Throwable ex) {
 383             // Wrap anything else in BootstrapMethodError
 384             throw new BootstrapMethodError("call site initialization exception", ex);
 385         }
 386         return site;
 387     }
 388 
 389     private static Object maybeReBox(Object x) {
 390         if (x instanceof Integer) {
 391             int xi = (int) x;
 392             if (xi == (byte) xi)
 393                 x = xi;  // must rebox; see JLS 5.1.7
 394         }
 395         return x;
 396     }
 397     private static void maybeReBoxElements(Object[] xa) {
 398         for (int i = 0; i < xa.length; i++) {
 399             xa[i] = maybeReBox(xa[i]);
 400         }
 401     }
 402 }