1 /*
   2  * Copyright (c) 2008, 2012, 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><!-- see indy-demo/src/PrintArgsDemo.java -->
  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 = type.invokers().uninitializedCallSite();
 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 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>
 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     static {
 221         try {
 222             GET_TARGET = IMPL_LOOKUP.
 223                 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
 224         } catch (ReflectiveOperationException e) {
 225             throw newInternalError(e);
 226         }
 227     }
 228 
 229     /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
 230     /*package-private*/
 231     static Empty uninitializedCallSite() {
 232         throw new IllegalStateException("uninitialized call site");
 233     }
 234 
 235     // unsafe stuff:
 236     private static final long TARGET_OFFSET;
 237     static {
 238         try {
 239             TARGET_OFFSET = UNSAFE.objectFieldOffset(CallSite.class.getDeclaredField("target"));
 240         } catch (Exception ex) { throw new Error(ex); }
 241     }
 242 
 243     /*package-private*/
 244     void setTargetNormal(MethodHandle newTarget) {
 245         MethodHandleNatives.setCallSiteTargetNormal(this, newTarget);
 246     }
 247     /*package-private*/
 248     MethodHandle getTargetVolatile() {
 249         return (MethodHandle) UNSAFE.getObjectVolatile(this, TARGET_OFFSET);
 250     }
 251     /*package-private*/
 252     void setTargetVolatile(MethodHandle newTarget) {
 253         MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget);
 254     }
 255 
 256     // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite:
 257     static CallSite makeSite(MethodHandle bootstrapMethod,
 258                              // Callee information:
 259                              String name, MethodType type,
 260                              // Extra arguments for BSM, if any:
 261                              Object info,
 262                              // Caller information:
 263                              Class<?> callerClass) {
 264         MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass);
 265         try {
 266             CallSite site;
 267             if(isLambdaMetafactory(bootstrapMethod, info)) { // LambdaMetafactory fastpath
 268                 Object[] argv = (Object[]) info;
 269                 site = LambdaMetafactory.metafactory(caller, name, type, (MethodType)argv[0], (MethodHandle)argv[1], (MethodType)argv[2]);
 270             } else {
 271                 Object binding;
 272                 info = maybeReBox(info);
 273                 if (info == null) {
 274                     binding = bootstrapMethod.invoke(caller, name, type);
 275                 } else if (!info.getClass().isArray()) {
 276                     binding = bootstrapMethod.invoke(caller, name, type, info);
 277                 } else {
 278                     Object[] argv = (Object[]) info;
 279                     maybeReBoxElements(argv);
 280                     if (3 + argv.length > 255)
 281                         throw new BootstrapMethodError("too many bootstrap method arguments");
 282                     MethodType bsmType = bootstrapMethod.type();
 283                     if (bsmType.parameterCount() == 4 && bsmType.parameterType(3) == Object[].class)
 284                         binding = bootstrapMethod.invoke(caller, name, type, argv);
 285                     else
 286                         binding = MethodHandles.spreadInvoker(bsmType, 3)
 287                                 .invoke(bootstrapMethod, caller, name, type, argv);
 288                 }
 289                 if (binding instanceof CallSite) {
 290                     site = (CallSite) binding;
 291                 } else {
 292                     throw new ClassCastException("bootstrap method failed to produce a CallSite");
 293                 }
 294             }
 295             if (!site.getTarget().type().equals(type))
 296                 throw new WrongMethodTypeException("wrong type: "+site.getTarget());
 297             return site;
 298         } catch (Throwable ex) {
 299             BootstrapMethodError bex;
 300             if (ex instanceof BootstrapMethodError)
 301                 bex = (BootstrapMethodError) ex;
 302             else
 303                 bex = new BootstrapMethodError("call site initialization exception", ex);
 304             throw bex;
 305         }
 306 
 307     }
 308 
 309     private static boolean isLambdaMetafactory(MethodHandle mh, Object info) {
 310         MemberName mn = mh.internalMemberName();
 311         if ((mn != null) &&
 312                 (mn.getDeclaringClass().equals(LambdaMetafactory.class)) &&
 313                 (mn.getName().equals("metafactory")) &&
 314                 (mn.getReferenceKind() == MethodHandleNatives.Constants.REF_invokeStatic) &&
 315                 (info instanceof Object[])) {
 316             Object[] argv = (Object[]) info;
 317             // checks info inconsistency -> let's slowpath throws all exceptions
 318             return (argv.length == 3) &&
 319                     (argv[0] instanceof MethodType) &&
 320                     (argv[1] instanceof MethodHandle) &&
 321                     (argv[2] instanceof MethodType);
 322         }
 323         return false;
 324     }
 325 
 326     private static Object maybeReBox(Object x) {
 327         if (x instanceof Integer) {
 328             int xi = (int) x;
 329             if (xi == (byte) xi)
 330                 x = xi;  // must rebox; see JLS 5.1.7
 331         }
 332         return x;
 333     }
 334     private static void maybeReBoxElements(Object[] xa) {
 335         for (int i = 0; i < xa.length; i++) {
 336             xa[i] = maybeReBox(xa[i]);
 337         }
 338     }
 339 }