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 // Android-changed: Not using Empty.
29 //import sun.invoke.empty.Empty;
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>{@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     // Android-changed: not used.
89     // static { MethodHandleImpl.initStatics(); }
90 
91     // The actual payload of this call site:
92     /*package-private*/
93     MethodHandle target;    // Note: This field is known to the JVM.  Do not change.
94 
95     /**
96      * Make a blank call site object with the given method type.
97      * An initial target method is supplied which will throw
98      * an {@link IllegalStateException} if called.
99      * <p>
100      * Before this {@code CallSite} object is returned from a bootstrap method,
101      * it is usually provided with a more useful target method,
102      * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
103      * @throws NullPointerException if the proposed type is null
104      */
105     /*package-private*/
CallSite(MethodType type)106     CallSite(MethodType type) {
107         // Android-changed: No cache for these.
108         // Instead create uninitializedCallSite target here using method handle transformations
109         // to create a method handle that has the expected method type but throws an
110         // IllegalStateException.
111         // target = makeUninitializedCallSite(type);
112         this.target = MethodHandles.throwException(type.returnType(), IllegalStateException.class);
113         this.target = MethodHandles.insertArguments(
114             this.target, 0, new IllegalStateException("uninitialized call site"));
115         if (type.parameterCount() > 0) {
116             this.target = MethodHandles.dropArguments(this.target, 0, type.ptypes());
117         }
118 
119         // Android-changed: Using initializer method for GET_TARGET instead of static initializer.
120         initializeGetTarget();
121     }
122 
123     /**
124      * Make a call site object equipped with an initial target method handle.
125      * @param target the method handle which will be the initial target of the call site
126      * @throws NullPointerException if the proposed target is null
127      */
128     /*package-private*/
CallSite(MethodHandle target)129     CallSite(MethodHandle target) {
130         target.type();  // null check
131         this.target = target;
132 
133         // Android-changed: Using initializer method for GET_TARGET instead of static initializer.
134         initializeGetTarget();
135     }
136 
137     /**
138      * Make a call site object equipped with an initial target method handle.
139      * @param targetType the desired type of the call site
140      * @param createTargetHook a hook which will bind the call site to the target method handle
141      * @throws WrongMethodTypeException if the hook cannot be invoked on the required arguments,
142      *         or if the target returned by the hook is not of the given {@code targetType}
143      * @throws NullPointerException if the hook returns a null value
144      * @throws ClassCastException if the hook returns something other than a {@code MethodHandle}
145      * @throws Throwable anything else thrown by the hook function
146      */
147     /*package-private*/
CallSite(MethodType targetType, MethodHandle createTargetHook)148     CallSite(MethodType targetType, MethodHandle createTargetHook) throws Throwable {
149         this(targetType);
150         ConstantCallSite selfCCS = (ConstantCallSite) this;
151         MethodHandle boundTarget = (MethodHandle) createTargetHook.invokeWithArguments(selfCCS);
152         checkTargetChange(this.target, boundTarget);
153         this.target = boundTarget;
154 
155         // Android-changed: Using initializer method for GET_TARGET instead of static initializer.
156         initializeGetTarget();
157     }
158 
159     /**
160      * Returns the type of this call site's target.
161      * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
162      * The {@code setTarget} method enforces this invariant by refusing any new target that does
163      * not have the previous target's type.
164      * @return the type of the current target, which is also the type of any future target
165      */
type()166     public MethodType type() {
167         // warning:  do not call getTarget here, because CCS.getTarget can throw IllegalStateException
168         return target.type();
169     }
170 
171     /**
172      * Returns the target method of the call site, according to the
173      * behavior defined by this call site's specific class.
174      * The immediate subclasses of {@code CallSite} document the
175      * class-specific behaviors of this method.
176      *
177      * @return the current linkage state of the call site, its target method handle
178      * @see ConstantCallSite
179      * @see VolatileCallSite
180      * @see #setTarget
181      * @see ConstantCallSite#getTarget
182      * @see MutableCallSite#getTarget
183      * @see VolatileCallSite#getTarget
184      */
getTarget()185     public abstract MethodHandle getTarget();
186 
187     /**
188      * Updates the target method of this call site, according to the
189      * behavior defined by this call site's specific class.
190      * The immediate subclasses of {@code CallSite} document the
191      * class-specific behaviors of this method.
192      * <p>
193      * The type of the new target must be {@linkplain MethodType#equals equal to}
194      * the type of the old target.
195      *
196      * @param newTarget the new target
197      * @throws NullPointerException if the proposed new target is null
198      * @throws WrongMethodTypeException if the proposed new target
199      *         has a method type that differs from the previous target
200      * @see CallSite#getTarget
201      * @see ConstantCallSite#setTarget
202      * @see MutableCallSite#setTarget
203      * @see VolatileCallSite#setTarget
204      */
setTarget(MethodHandle newTarget)205     public abstract void setTarget(MethodHandle newTarget);
206 
checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget)207     void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
208         MethodType oldType = oldTarget.type();
209         MethodType newType = newTarget.type();  // null check!
210         if (!newType.equals(oldType))
211             throw wrongTargetType(newTarget, oldType);
212     }
213 
wrongTargetType(MethodHandle target, MethodType type)214     private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
215         return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
216     }
217 
218     /**
219      * Produces a method handle equivalent to an invokedynamic instruction
220      * which has been linked to this call site.
221      * <p>
222      * This method is equivalent to the following code:
223      * <blockquote><pre>{@code
224      * MethodHandle getTarget, invoker, result;
225      * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
226      * invoker = MethodHandles.exactInvoker(this.type());
227      * result = MethodHandles.foldArguments(invoker, getTarget)
228      * }</pre></blockquote>
229      *
230      * @return a method handle which always invokes this call site's current target
231      */
dynamicInvoker()232     public abstract MethodHandle dynamicInvoker();
233 
makeDynamicInvoker()234     /*non-public*/ MethodHandle makeDynamicInvoker() {
235         // Android-changed: Use bindTo() rather than bindArgumentL() (not implemented).
236         MethodHandle getTarget = GET_TARGET.bindTo(this);
237         MethodHandle invoker = MethodHandles.exactInvoker(this.type());
238         return MethodHandles.foldArguments(invoker, getTarget);
239     }
240 
241     // Android-changed: no longer final. GET_TARGET assigned in initializeGetTarget().
242     private static MethodHandle GET_TARGET = null;
243 
initializeGetTarget()244     private void initializeGetTarget() {
245         // Android-changed: moved from static initializer for GET_TARGET.
246         // This avoids issues with running early. Called from constructors.
247         // CallSite creation is not performance critical.
248         synchronized (CallSite.class) {
249             if (GET_TARGET == null) {
250                 try {
251                     GET_TARGET = IMPL_LOOKUP.
252                             findVirtual(CallSite.class, "getTarget",
253                                         MethodType.methodType(MethodHandle.class));
254                 } catch (ReflectiveOperationException e) {
255                     throw new InternalError(e);
256                 }
257             }
258         }
259     }
260 
261     // Android-changed: not used.
262     // /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
263     // /*package-private*/
264     // static Empty uninitializedCallSite() {
265     //     throw new IllegalStateException("uninitialized call site");
266     // }
267 
268     // unsafe stuff:
269     private static final long TARGET_OFFSET;
270     static {
271         try {
272             TARGET_OFFSET = UNSAFE.objectFieldOffset(CallSite.class.getDeclaredField("target"));
273         } catch (Exception ex) { throw new Error(ex); }
274     }
275 
276     /*package-private*/
setTargetNormal(MethodHandle newTarget)277     void setTargetNormal(MethodHandle newTarget) {
278         // Android-changed: Set value directly.
279         // MethodHandleNatives.setCallSiteTargetNormal(this, newTarget);
280         target = newTarget;
281     }
282     /*package-private*/
getTargetVolatile()283     MethodHandle getTargetVolatile() {
284         return (MethodHandle) UNSAFE.getObjectVolatile(this, TARGET_OFFSET);
285     }
286     /*package-private*/
setTargetVolatile(MethodHandle newTarget)287     void setTargetVolatile(MethodHandle newTarget) {
288         // Android-changed: Set value directly.
289         // MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget);
290         UNSAFE.putObjectVolatile(this, TARGET_OFFSET, newTarget);
291     }
292 
293     // Android-changed: not used.
294     // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite:
295     // static CallSite makeSite(MethodHandle bootstrapMethod,
296     //                          // Callee information:
297     //                          String name, MethodType type,
298     //                          // Extra arguments for BSM, if any:
299     //                          Object info,
300     //                          // Caller information:
301     //                          Class<?> callerClass) {
302     //     MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass);
303     //     CallSite site;
304     //     try {
305     //         Object binding;
306     //         info = maybeReBox(info);
307     //         if (info == null) {
308     //             binding = bootstrapMethod.invoke(caller, name, type);
309     //         } else if (!info.getClass().isArray()) {
310     //             binding = bootstrapMethod.invoke(caller, name, type, info);
311     //         } else {
312     //             Object[] argv = (Object[]) info;
313     //             maybeReBoxElements(argv);
314     //             switch (argv.length) {
315     //             case 0:
316     //                 binding = bootstrapMethod.invoke(caller, name, type);
317     //                 break;
318     //             case 1:
319     //                 binding = bootstrapMethod.invoke(caller, name, type,
320     //                                                  argv[0]);
321     //                 break;
322     //             case 2:
323     //                 binding = bootstrapMethod.invoke(caller, name, type,
324     //                                                  argv[0], argv[1]);
325     //                 break;
326     //             case 3:
327     //                 binding = bootstrapMethod.invoke(caller, name, type,
328     //                                                  argv[0], argv[1], argv[2]);
329     //                 break;
330     //             case 4:
331     //                 binding = bootstrapMethod.invoke(caller, name, type,
332     //                                                  argv[0], argv[1], argv[2], argv[3]);
333     //                 break;
334     //             case 5:
335     //                 binding = bootstrapMethod.invoke(caller, name, type,
336     //                                                  argv[0], argv[1], argv[2], argv[3], argv[4]);
337     //                 break;
338     //             case 6:
339     //                 binding = bootstrapMethod.invoke(caller, name, type,
340     //                                                  argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
341     //                 break;
342     //             default:
343     //                 final int NON_SPREAD_ARG_COUNT = 3;  // (caller, name, type)
344     //                 if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY)
345     //                     throw new BootstrapMethodError("too many bootstrap method arguments");
346     //                 MethodType bsmType = bootstrapMethod.type();
347     //                 MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length);
348     //                 MethodHandle typedBSM = bootstrapMethod.asType(invocationType);
349     //                 MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT);
350     //                 binding = spreader.invokeExact(typedBSM, (Object)caller, (Object)name, (Object)type, argv);
351     //             }
352     //         }
353     //         //System.out.println("BSM for "+name+type+" => "+binding);
354     //         if (binding instanceof CallSite) {
355     //             site = (CallSite) binding;
356     //         }  else {
357     //             throw new ClassCastException("bootstrap method failed to produce a CallSite");
358     //         }
359     //         if (!site.getTarget().type().equals(type))
360     //             throw wrongTargetType(site.getTarget(), type);
361     //     } catch (Throwable ex) {
362     //         BootstrapMethodError bex;
363     //         if (ex instanceof BootstrapMethodError)
364     //             bex = (BootstrapMethodError) ex;
365     //         else
366     //             bex = new BootstrapMethodError("call site initialization exception", ex);
367     //         throw bex;
368     //     }
369     //     return site;
370     // }
371 
372     // private static Object maybeReBox(Object x) {
373     //     if (x instanceof Integer) {
374     //         int xi = (int) x;
375     //         if (xi == (byte) xi)
376     //             x = xi;  // must rebox; see JLS 5.1.7
377     //     }
378     //     return x;
379     // }
380     // private static void maybeReBoxElements(Object[] xa) {
381     //     for (int i = 0; i < xa.length; i++) {
382     //         xa[i] = maybeReBox(xa[i]);
383     //     }
384     // }
385 }
386