1 /*
   2  * Copyright (c) 2008, 2011, 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 sun.misc.Unsafe;
  30 import static java.lang.invoke.MethodHandleStatics.*;
  31 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  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><!-- see indy-demo/src/PrintArgsDemo.java -->
  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     static { MethodHandleImpl.initStatics(); }
  89 
  90     // Fields used only by the JVM.  Do not use or change.
  91     private MemberName vmmethod; // supplied by the JVM (ref. to calling method)
  92     private int        vmindex;  // supplied by the JVM (BCI within calling method)
  93 
  94     // The actual payload of this call site:
  95     /*package-private*/
  96     MethodHandle target;
  97 
  98     /**
  99      * Make a blank call site object with the given method type.
 100      * An initial target method is supplied which will throw
 101      * an {@link IllegalStateException} if called.
 102      * <p>
 103      * Before this {@code CallSite} object is returned from a bootstrap method,
 104      * it is usually provided with a more useful target method,
 105      * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
 106      * @throws NullPointerException if the proposed type is null
 107      */
 108     /*package-private*/
 109     CallSite(MethodType type) {
 110         target = type.invokers().uninitializedCallSite();
 111     }
 112 
 113     /**
 114      * Make a call site object equipped with an initial target method handle.
 115      * @param target the method handle which will be the initial target of the call site
 116      * @throws NullPointerException if the proposed target is null
 117      */
 118     /*package-private*/
 119     CallSite(MethodHandle target) {
 120         target.type();  // null check
 121         this.target = target;
 122     }
 123 
 124     /**
 125      * Make a call site object equipped with an initial target method handle.
 126      * @param targetType the desired type of the call site
 127      * @param createTargetHook a hook which will bind the call site to the target method handle
 128      * @throws WrongMethodTypeException if the hook cannot be invoked on the required arguments,
 129      *         or if the target returned by the hook is not of the given {@code targetType}
 130      * @throws NullPointerException if the hook returns a null value
 131      * @throws ClassCastException if the hook returns something other than a {@code MethodHandle}
 132      * @throws Throwable anything else thrown by the the hook function
 133      */
 134     /*package-private*/
 135     CallSite(MethodType targetType, MethodHandle createTargetHook) throws Throwable {
 136         this(targetType);
 137         ConstantCallSite selfCCS = (ConstantCallSite) this;
 138         MethodHandle boundTarget = (MethodHandle) createTargetHook.invokeWithArguments(selfCCS);
 139         checkTargetChange(this.target, boundTarget);
 140         this.target = boundTarget;
 141     }
 142 
 143     /**
 144      * Returns the type of this call site's target.
 145      * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
 146      * The {@code setTarget} method enforces this invariant by refusing any new target that does
 147      * not have the previous target's type.
 148      * @return the type of the current target, which is also the type of any future target
 149      */
 150     public MethodType type() {
 151         // warning:  do not call getTarget here, because CCS.getTarget can throw IllegalStateException
 152         return target.type();
 153     }
 154 
 155     /** Called from JVM (or low-level Java code) after the BSM returns the newly created CallSite.
 156      *  The parameters are JVM-specific.
 157      */
 158     void initializeFromJVM(String name,
 159                            MethodType type,
 160                            MemberName callerMethod,
 161                            int        callerBCI) {
 162         if (this.vmmethod != null) {
 163             // FIXME
 164             throw new BootstrapMethodError("call site has already been linked to an invokedynamic instruction");
 165         }
 166         if (!this.type().equals(type)) {
 167             throw wrongTargetType(target, type);
 168         }
 169         this.vmindex  = callerBCI;
 170         this.vmmethod = callerMethod;
 171     }
 172 
 173     /**
 174      * Returns the target method of the call site, according to the
 175      * behavior defined by this call site's specific class.
 176      * The immediate subclasses of {@code CallSite} document the
 177      * class-specific behaviors of this method.
 178      *
 179      * @return the current linkage state of the call site, its target method handle
 180      * @see ConstantCallSite
 181      * @see VolatileCallSite
 182      * @see #setTarget
 183      * @see ConstantCallSite#getTarget
 184      * @see MutableCallSite#getTarget
 185      * @see VolatileCallSite#getTarget
 186      */
 187     public abstract MethodHandle getTarget();
 188 
 189     /**
 190      * Updates the target method of this call site, according to the
 191      * behavior defined by this call site's specific class.
 192      * The immediate subclasses of {@code CallSite} document the
 193      * class-specific behaviors of this method.
 194      * <p>
 195      * The type of the new target must be {@linkplain MethodType#equals equal to}
 196      * the type of the old target.
 197      *
 198      * @param newTarget the new target
 199      * @throws NullPointerException if the proposed new target is null
 200      * @throws WrongMethodTypeException if the proposed new target
 201      *         has a method type that differs from the previous target
 202      * @see CallSite#getTarget
 203      * @see ConstantCallSite#setTarget
 204      * @see MutableCallSite#setTarget
 205      * @see VolatileCallSite#setTarget
 206      */
 207     public abstract void setTarget(MethodHandle newTarget);
 208 
 209     void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
 210         MethodType oldType = oldTarget.type();
 211         MethodType newType = newTarget.type();  // null check!
 212         if (!newType.equals(oldType))
 213             throw wrongTargetType(newTarget, oldType);
 214     }
 215 
 216     private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
 217         return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
 218     }
 219 
 220     /**
 221      * Produces a method handle equivalent to an invokedynamic instruction
 222      * which has been linked to this call site.
 223      * <p>
 224      * This method is equivalent to the following code:
 225      * <blockquote><pre>
 226      * MethodHandle getTarget, invoker, result;
 227      * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
 228      * invoker = MethodHandles.exactInvoker(this.type());
 229      * result = MethodHandles.foldArguments(invoker, getTarget)
 230      * </pre></blockquote>
 231      *
 232      * @return a method handle which always invokes this call site's current target
 233      */
 234     public abstract MethodHandle dynamicInvoker();
 235 
 236     /*non-public*/ MethodHandle makeDynamicInvoker() {
 237         MethodHandle getTarget = MethodHandleImpl.bindReceiver(GET_TARGET, this);
 238         MethodHandle invoker = MethodHandles.exactInvoker(this.type());
 239         return MethodHandles.foldArguments(invoker, getTarget);
 240     }
 241 
 242     private static final MethodHandle GET_TARGET;
 243     static {
 244         try {
 245             GET_TARGET = IMPL_LOOKUP.
 246                 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
 247         } catch (ReflectiveOperationException ignore) {
 248             throw new InternalError();
 249         }
 250     }
 251 
 252     /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
 253     /*package-private*/
 254     static Empty uninitializedCallSite() {
 255         throw new IllegalStateException("uninitialized call site");
 256     }
 257 
 258     // unsafe stuff:
 259     private static final Unsafe unsafe = Unsafe.getUnsafe();
 260     private static final long TARGET_OFFSET;
 261 
 262     static {
 263         try {
 264             TARGET_OFFSET = unsafe.objectFieldOffset(CallSite.class.getDeclaredField("target"));
 265         } catch (Exception ex) { throw new Error(ex); }
 266     }
 267 
 268     /*package-private*/
 269     void setTargetNormal(MethodHandle newTarget) {
 270         target = newTarget;
 271     }
 272     /*package-private*/
 273     MethodHandle getTargetVolatile() {
 274         return (MethodHandle) unsafe.getObjectVolatile(this, TARGET_OFFSET);
 275     }
 276     /*package-private*/
 277     void setTargetVolatile(MethodHandle newTarget) {
 278         unsafe.putObjectVolatile(this, TARGET_OFFSET, newTarget);
 279     }
 280 
 281     // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite:
 282     static CallSite makeSite(MethodHandle bootstrapMethod,
 283                              // Callee information:
 284                              String name, MethodType type,
 285                              // Extra arguments for BSM, if any:
 286                              Object info,
 287                              // Caller information:
 288                              MemberName callerMethod, int callerBCI) {
 289         Class<?> callerClass = callerMethod.getDeclaringClass();
 290         Object caller = IMPL_LOOKUP.in(callerClass);
 291         CallSite site;
 292         try {
 293             Object binding;
 294             info = maybeReBox(info);
 295             if (info == null) {
 296                 binding = bootstrapMethod.invoke(caller, name, type);
 297             } else if (!info.getClass().isArray()) {
 298                 binding = bootstrapMethod.invoke(caller, name, type, info);
 299             } else {
 300                 Object[] argv = (Object[]) info;
 301                 maybeReBoxElements(argv);
 302                 if (3 + argv.length > 255)
 303                     throw new BootstrapMethodError("too many bootstrap method arguments");
 304                 MethodType bsmType = bootstrapMethod.type();
 305                 if (bsmType.parameterCount() == 4 && bsmType.parameterType(3) == Object[].class)
 306                     binding = bootstrapMethod.invoke(caller, name, type, argv);
 307                 else
 308                     binding = MethodHandles.spreadInvoker(bsmType, 3)
 309                         .invoke(bootstrapMethod, caller, name, type, argv);
 310             }
 311             //System.out.println("BSM for "+name+type+" => "+binding);
 312             if (binding instanceof CallSite) {
 313                 site = (CallSite) binding;
 314             }  else {
 315                 throw new ClassCastException("bootstrap method failed to produce a CallSite");
 316             }
 317             if (!site.getTarget().type().equals(type))
 318                 throw new WrongMethodTypeException("wrong type: "+site.getTarget());
 319         } catch (Throwable ex) {
 320             BootstrapMethodError bex;
 321             if (ex instanceof BootstrapMethodError)
 322                 bex = (BootstrapMethodError) ex;
 323             else
 324                 bex = new BootstrapMethodError("call site initialization exception", ex);
 325             throw bex;
 326         }
 327         return site;
 328     }
 329 
 330     private static Object maybeReBox(Object x) {
 331         if (x instanceof Integer) {
 332             int xi = (int) x;
 333             if (xi == (byte) xi)
 334                 x = xi;  // must rebox; see JLS 5.1.7
 335         }
 336         return x;
 337     }
 338     private static void maybeReBoxElements(Object[] xa) {
 339         for (int i = 0; i < xa.length; i++) {
 340             xa[i] = maybeReBox(xa[i]);
 341         }
 342     }
 343 }