Batch of classes necessary to implement invoke dynamic interfaces. Taken from JDK8 build 132
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.
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.
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).
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.
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
26 package java.lang.invoke;
28 import sun.invoke.empty.Empty;
29 import static java.lang.invoke.MethodHandleStatics.*;
30 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
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}.
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.
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.
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.
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);
68 private static void printArgs(Object... args) {
69 System.out.println(java.util.Arrays.deepToString(args));
71 private static final MethodHandle printArgs;
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));
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));
83 * @author John Rose, JSR 292 EG
86 public class CallSite {
87 static { MethodHandleImpl.initStatics(); }
89 // The actual payload of this call site:
91 MethodHandle target; // Note: This field is known to the JVM. Do not change.
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.
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
104 CallSite(MethodType type) {
105 target = type.invokers().uninitializedCallSite();
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
114 CallSite(MethodHandle target) {
115 target.type(); // null check
116 this.target = target;
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
130 CallSite(MethodType targetType, MethodHandle createTargetHook) throws Throwable {
132 ConstantCallSite selfCCS = (ConstantCallSite) this;
133 MethodHandle boundTarget = (MethodHandle) createTargetHook.invokeWithArguments(selfCCS);
134 checkTargetChange(this.target, boundTarget);
135 this.target = boundTarget;
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
145 public MethodType type() {
146 // warning: do not call getTarget here, because CCS.getTarget can throw IllegalStateException
147 return target.type();
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.
156 * @return the current linkage state of the call site, its target method handle
157 * @see ConstantCallSite
158 * @see VolatileCallSite
160 * @see ConstantCallSite#getTarget
161 * @see MutableCallSite#getTarget
162 * @see VolatileCallSite#getTarget
164 public abstract MethodHandle getTarget();
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.
172 * The type of the new target must be {@linkplain MethodType#equals equal to}
173 * the type of the old target.
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
184 public abstract void setTarget(MethodHandle newTarget);
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);
193 private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
194 return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
198 * Produces a method handle equivalent to an invokedynamic instruction
199 * which has been linked to this call site.
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>
209 * @return a method handle which always invokes this call site's current target
211 public abstract MethodHandle dynamicInvoker();
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);
219 private static final MethodHandle GET_TARGET;
222 GET_TARGET = IMPL_LOOKUP.
223 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
224 } catch (ReflectiveOperationException e) {
225 throw newInternalError(e);
229 /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
231 static Empty uninitializedCallSite() {
232 throw new IllegalStateException("uninitialized call site");
236 private static final long TARGET_OFFSET;
239 TARGET_OFFSET = UNSAFE.objectFieldOffset(CallSite.class.getDeclaredField("target"));
240 } catch (Exception ex) { throw new Error(ex); }
244 void setTargetNormal(MethodHandle newTarget) {
245 MethodHandleNatives.setCallSiteTargetNormal(this, newTarget);
248 MethodHandle getTargetVolatile() {
249 return (MethodHandle) UNSAFE.getObjectVolatile(this, TARGET_OFFSET);
252 void setTargetVolatile(MethodHandle newTarget) {
253 MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget);
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:
262 // Caller information:
263 Class<?> callerClass) {
264 MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass);
268 info = maybeReBox(info);
270 binding = bootstrapMethod.invoke(caller, name, type);
271 } else if (!info.getClass().isArray()) {
272 binding = bootstrapMethod.invoke(caller, name, type, info);
274 Object[] argv = (Object[]) info;
275 maybeReBoxElements(argv);
276 switch (argv.length) {
278 binding = bootstrapMethod.invoke(caller, name, type);
281 binding = bootstrapMethod.invoke(caller, name, type,
285 binding = bootstrapMethod.invoke(caller, name, type,
289 binding = bootstrapMethod.invoke(caller, name, type,
290 argv[0], argv[1], argv[2]);
293 binding = bootstrapMethod.invoke(caller, name, type,
294 argv[0], argv[1], argv[2], argv[3]);
297 binding = bootstrapMethod.invoke(caller, name, type,
298 argv[0], argv[1], argv[2], argv[3], argv[4]);
301 binding = bootstrapMethod.invoke(caller, name, type,
302 argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
305 final int NON_SPREAD_ARG_COUNT = 3; // (caller, name, type)
306 if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY)
307 throw new BootstrapMethodError("too many bootstrap method arguments");
308 MethodType bsmType = bootstrapMethod.type();
309 MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length);
310 MethodHandle typedBSM = bootstrapMethod.asType(invocationType);
311 MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT);
312 binding = spreader.invokeExact(typedBSM, (Object)caller, (Object)name, (Object)type, argv);
315 //System.out.println("BSM for "+name+type+" => "+binding);
316 if (binding instanceof CallSite) {
317 site = (CallSite) binding;
319 throw new ClassCastException("bootstrap method failed to produce a CallSite");
321 if (!site.getTarget().type().equals(type))
322 throw new WrongMethodTypeException("wrong type: "+site.getTarget());
323 } catch (Throwable ex) {
324 BootstrapMethodError bex;
325 if (ex instanceof BootstrapMethodError)
326 bex = (BootstrapMethodError) ex;
328 bex = new BootstrapMethodError("call site initialization exception", ex);
334 private static Object maybeReBox(Object x) {
335 if (x instanceof Integer) {
338 x = xi; // must rebox; see JLS 5.1.7
342 private static void maybeReBoxElements(Object[] xa) {
343 for (int i = 0; i < xa.length; i++) {
344 xa[i] = maybeReBox(xa[i]);