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 sun.invoke.empty.Empty;
  29 import static java.lang.invoke.MethodHandleStatics.*;
  30 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  31 
  32 /**
  33  * A {@code CallSite} is a holder for a variable {@link MethodHandle},
  34  * which is called its {@code target}.
  35  * An {@code invokedynamic} instruction linked to a {@code CallSite} delegates
  36  * all calls to the site's current target.
  37  * A {@code CallSite} may be associated with several {@code invokedynamic}
  38  * instructions, or it may be "free floating", associated with none.
  39  * In any case, it may be invoked through an associated method handle
  40  * called its {@linkplain #dynamicInvoker dynamic invoker}.
  41  * <p>
  42  * {@code CallSite} is an abstract class which does not allow
  43  * direct subclassing by users.  It has three immediate,
  44  * concrete subclasses that may be either instantiated or subclassed.
  45  * <ul>
  46  * <li>If a mutable target is not required, an {@code invokedynamic} instruction
  47  * may be permanently bound by means of a {@linkplain ConstantCallSite constant call site}.
  48  * <li>If a mutable target is required which has volatile variable semantics,
  49  * because updates to the target must be immediately and reliably witnessed by other threads,
  50  * a {@linkplain VolatileCallSite volatile call site} may be used.
  51  * <li>Otherwise, if a mutable target is required,
  52  * a {@linkplain MutableCallSite mutable call site} may be used.
  53  * </ul>
  54  * <p>
  55  * A non-constant call site may be <em>relinked</em> by changing its target.
  56  * The new target must have the same {@linkplain MethodHandle#type() type}
  57  * as the previous target.
  58  * Thus, though a call site can be relinked to a series of
  59  * successive targets, it cannot change its type.
  60  * <p>
  61  * Here is a sample use of call sites and bootstrap methods which links every
  62  * dynamic call site to print its arguments:
  63 <blockquote><pre>{@code
  64 static void test() throws Throwable {
  65     // THE FOLLOWING LINE IS PSEUDOCODE FOR A JVM INSTRUCTION
  66     InvokeDynamic[#bootstrapDynamic].baz("baz arg", 2, 3.14);
  67 }
  68 private static void printArgs(Object... args) {
  69   System.out.println(java.util.Arrays.deepToString(args));
  70 }
  71 private static final MethodHandle printArgs;
  72 static {
  73   MethodHandles.Lookup lookup = MethodHandles.lookup();
  74   Class thisClass = lookup.lookupClass();  // (who am I?)
  75   printArgs = lookup.findStatic(thisClass,
  76       "printArgs", MethodType.methodType(void.class, Object[].class));
  77 }
  78 private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String name, MethodType type) {
  79   // ignore caller and name, but match the type:
  80   return new ConstantCallSite(printArgs.asType(type));
  81 }
  82 }</pre></blockquote>
  83  * @author John Rose, JSR 292 EG
  84  */
  85 abstract
  86 public class CallSite {
  87     static { MethodHandleImpl.initStatics(); }
  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      * Returns the type of this call site's target.
 140      * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
 141      * The {@code setTarget} method enforces this invariant by refusing any new target that does
 142      * not have the previous target's type.
 143      * @return the type of the current target, which is also the type of any future target
 144      */
 145     public MethodType type() {
 146         // warning:  do not call getTarget here, because CCS.getTarget can throw IllegalStateException
 147         return target.type();
 148     }
 149 
 150     /**
 151      * Returns the target method of the call site, according to the
 152      * behavior defined by this call site's specific class.
 153      * The immediate subclasses of {@code CallSite} document the
 154      * class-specific behaviors of this method.
 155      *
 156      * @return the current linkage state of the call site, its target method handle
 157      * @see ConstantCallSite
 158      * @see VolatileCallSite
 159      * @see #setTarget
 160      * @see ConstantCallSite#getTarget
 161      * @see MutableCallSite#getTarget
 162      * @see VolatileCallSite#getTarget
 163      */
 164     public abstract MethodHandle getTarget();
 165 
 166     /**
 167      * Updates the target method of this call site, according to the
 168      * behavior defined by this call site's specific class.
 169      * The immediate subclasses of {@code CallSite} document the
 170      * class-specific behaviors of this method.
 171      * <p>
 172      * The type of the new target must be {@linkplain MethodType#equals equal to}
 173      * the type of the old target.
 174      *
 175      * @param newTarget the new target
 176      * @throws NullPointerException if the proposed new target is null
 177      * @throws WrongMethodTypeException if the proposed new target
 178      *         has a method type that differs from the previous target
 179      * @see CallSite#getTarget
 180      * @see ConstantCallSite#setTarget
 181      * @see MutableCallSite#setTarget
 182      * @see VolatileCallSite#setTarget
 183      */
 184     public abstract void setTarget(MethodHandle newTarget);
 185 
 186     void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
 187         MethodType oldType = oldTarget.type();
 188         MethodType newType = newTarget.type();  // null check!
 189         if (!newType.equals(oldType))
 190             throw wrongTargetType(newTarget, oldType);
 191     }
 192 
 193     private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
 194         return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
 195     }
 196 
 197     /**
 198      * Produces a method handle equivalent to an invokedynamic instruction
 199      * which has been linked to this call site.
 200      * <p>
 201      * This method is equivalent to the following code:
 202      * <blockquote><pre>{@code
 203      * MethodHandle getTarget, invoker, result;
 204      * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
 205      * invoker = MethodHandles.exactInvoker(this.type());
 206      * result = MethodHandles.foldArguments(invoker, getTarget)
 207      * }</pre></blockquote>
 208      *
 209      * @return a method handle which always invokes this call site's current target
 210      */
 211     public abstract MethodHandle dynamicInvoker();
 212 
 213     /*non-public*/ MethodHandle makeDynamicInvoker() {
 214         MethodHandle getTarget = GET_TARGET.bindReceiver(this);
 215         MethodHandle invoker = MethodHandles.exactInvoker(this.type());
 216         return MethodHandles.foldArguments(invoker, getTarget);
 217     }
 218 
 219     private static final MethodHandle GET_TARGET;
 220     private static final MethodHandle THROW_UCS;
 221     static {
 222         try {
 223             GET_TARGET = IMPL_LOOKUP.
 224                 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
 225             THROW_UCS = IMPL_LOOKUP.
 226                 findStatic(CallSite.class, "uninitializedCallSite", MethodType.methodType(Object.class, Object[].class));
 227         } catch (ReflectiveOperationException e) {
 228             throw newInternalError(e);
 229         }
 230     }
 231 
 232     /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
 233     private static Object uninitializedCallSite(Object... ignore) {
 234         throw new IllegalStateException("uninitialized call site");
 235     }
 236 
 237     private MethodHandle makeUninitializedCallSite(MethodType targetType) {
 238         MethodType basicType = targetType.basicType();
 239         MethodHandle invoker = basicType.form().cachedMethodHandle(MethodTypeForm.MH_UNINIT_CS);
 240         if (invoker == null) {
 241             invoker = THROW_UCS.asType(basicType);
 242             invoker = basicType.form().setCachedMethodHandle(MethodTypeForm.MH_UNINIT_CS, invoker);
 243         }
 244         // unchecked view is OK since no values will be received or returned
 245         return invoker.viewAsType(targetType);
 246     }
 247 
 248     // unsafe stuff:
 249     private static final long TARGET_OFFSET;
 250     static {
 251         try {
 252             TARGET_OFFSET = UNSAFE.objectFieldOffset(CallSite.class.getDeclaredField("target"));
 253         } catch (Exception ex) { throw new Error(ex); }
 254     }
 255 
 256     /*package-private*/
 257     void setTargetNormal(MethodHandle newTarget) {
 258         MethodHandleNatives.setCallSiteTargetNormal(this, newTarget);
 259     }
 260     /*package-private*/
 261     MethodHandle getTargetVolatile() {
 262         return (MethodHandle) UNSAFE.getObjectVolatile(this, TARGET_OFFSET);
 263     }
 264     /*package-private*/
 265     void setTargetVolatile(MethodHandle newTarget) {
 266         MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget);
 267     }
 268 
 269     // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite:
 270     static CallSite makeSite(MethodHandle bootstrapMethod,
 271                              // Callee information:
 272                              String name, MethodType type,
 273                              // Extra arguments for BSM, if any:
 274                              Object info,
 275                              // Caller information:
 276                              Class<?> callerClass) {
 277         MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass);
 278         CallSite site;
 279         try {
 280             Object binding;
 281             info = maybeReBox(info);
 282             if (info == null) {
 283                 binding = bootstrapMethod.invoke(caller, name, type);
 284             } else if (!info.getClass().isArray()) {
 285                 binding = bootstrapMethod.invoke(caller, name, type, info);
 286             } else {
 287                 Object[] argv = (Object[]) info;
 288                 maybeReBoxElements(argv);
 289                 switch (argv.length) {
 290                 case 0:
 291                     binding = bootstrapMethod.invoke(caller, name, type);
 292                     break;
 293                 case 1:
 294                     binding = bootstrapMethod.invoke(caller, name, type,
 295                                                      argv[0]);
 296                     break;
 297                 case 2:
 298                     binding = bootstrapMethod.invoke(caller, name, type,
 299                                                      argv[0], argv[1]);
 300                     break;
 301                 case 3:
 302                     binding = bootstrapMethod.invoke(caller, name, type,
 303                                                      argv[0], argv[1], argv[2]);
 304                     break;
 305                 case 4:
 306                     binding = bootstrapMethod.invoke(caller, name, type,
 307                                                      argv[0], argv[1], argv[2], argv[3]);
 308                     break;
 309                 case 5:
 310                     binding = bootstrapMethod.invoke(caller, name, type,
 311                                                      argv[0], argv[1], argv[2], argv[3], argv[4]);
 312                     break;
 313                 case 6:
 314                     binding = bootstrapMethod.invoke(caller, name, type,
 315                                                      argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
 316                     break;
 317                 default:
 318                     final int NON_SPREAD_ARG_COUNT = 3;  // (caller, name, type)
 319                     if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY)
 320                         throw new BootstrapMethodError("too many bootstrap method arguments");
 321                     MethodType bsmType = bootstrapMethod.type();
 322                     MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length);
 323                     MethodHandle typedBSM = bootstrapMethod.asType(invocationType);
 324                     MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT);
 325                     binding = spreader.invokeExact(typedBSM, (Object)caller, (Object)name, (Object)type, argv);
 326                 }
 327             }
 328             //System.out.println("BSM for "+name+type+" => "+binding);
 329             if (binding instanceof CallSite) {
 330                 site = (CallSite) binding;
 331             }  else {
 332                 throw new ClassCastException("bootstrap method failed to produce a CallSite");
 333             }
 334             if (!site.getTarget().type().equals(type))
 335                 throw wrongTargetType(site.getTarget(), type);
 336         } catch (Throwable ex) {
 337             BootstrapMethodError bex;
 338             if (ex instanceof BootstrapMethodError)
 339                 bex = (BootstrapMethodError) ex;
 340             else
 341                 bex = new BootstrapMethodError("call site initialization exception", ex);
 342             throw bex;
 343         }
 344         return site;
 345     }
 346 
 347     private static Object maybeReBox(Object x) {
 348         if (x instanceof Integer) {
 349             int xi = (int) x;
 350             if (xi == (byte) xi)
 351                 x = xi;  // must rebox; see JLS 5.1.7
 352         }
 353         return x;
 354     }
 355     private static void maybeReBoxElements(Object[] xa) {
 356         for (int i = 0; i < xa.length; i++) {
 357             xa[i] = maybeReBox(xa[i]);
 358         }
 359     }
 360 }