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 static java.lang.invoke.MethodHandleStatics.*; 29 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; 30 import sun.misc.Cleaner; 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 * {@code CallSite} dependency context. 140 * JVM uses CallSite.context to store nmethod dependencies on the call site target. 141 */ 142 private final Context context = Context.make(this); 143 144 static class Context implements Runnable { 145 static { 146 sun.reflect.Reflection.registerFieldsToFilter(Context.class, "dependencies"); 147 } 148 149 private final long dependencies = 0; // Used by JVM to store JVM_nmethodBucket* 150 151 static Context make(CallSite cs) { 152 final Context newContext = new Context(); 153 // Cleaner is attached to CallSite instance and it clears native structures allocated for CallSite context. 154 // Though the CallSite can become unreachable, its Context is retained by the Cleaner instance (which is 155 // referenced from Cleaner class) until cleanup is performed. 156 Cleaner.create(cs, newContext); 157 return newContext; 158 } 159 160 @Override 161 public void run() { 162 MethodHandleNatives.clearCallSiteContext(this); 163 } 164 } 165 166 /** 167 * Returns the type of this call site's target. 168 * Although targets may change, any call site's type is permanent, and can never change to an unequal type. 169 * The {@code setTarget} method enforces this invariant by refusing any new target that does 170 * not have the previous target's type. 171 * @return the type of the current target, which is also the type of any future target 172 */ 173 public MethodType type() { 174 // warning: do not call getTarget here, because CCS.getTarget can throw IllegalStateException 175 return target.type(); 176 } 177 178 /** 179 * Returns the target method of the call site, according to the 180 * behavior defined by this call site's specific class. 181 * The immediate subclasses of {@code CallSite} document the 182 * class-specific behaviors of this method. 183 * 184 * @return the current linkage state of the call site, its target method handle 185 * @see ConstantCallSite 186 * @see VolatileCallSite 187 * @see #setTarget 188 * @see ConstantCallSite#getTarget 189 * @see MutableCallSite#getTarget 190 * @see VolatileCallSite#getTarget 191 */ 192 public abstract MethodHandle getTarget(); 193 194 /** 195 * Updates the target method of this call site, according to the 196 * behavior defined by this call site's specific class. 197 * The immediate subclasses of {@code CallSite} document the 198 * class-specific behaviors of this method. 199 * <p> 200 * The type of the new target must be {@linkplain MethodType#equals equal to} 201 * the type of the old target. 202 * 203 * @param newTarget the new target 204 * @throws NullPointerException if the proposed new target is null 205 * @throws WrongMethodTypeException if the proposed new target 206 * has a method type that differs from the previous target 207 * @see CallSite#getTarget 208 * @see ConstantCallSite#setTarget 209 * @see MutableCallSite#setTarget 210 * @see VolatileCallSite#setTarget 211 */ 212 public abstract void setTarget(MethodHandle newTarget); 213 214 void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) { 215 MethodType oldType = oldTarget.type(); 216 MethodType newType = newTarget.type(); // null check! 217 if (!newType.equals(oldType)) 218 throw wrongTargetType(newTarget, oldType); 219 } 220 221 private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) { 222 return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type); 223 } 224 225 /** 226 * Produces a method handle equivalent to an invokedynamic instruction 227 * which has been linked to this call site. 228 * <p> 229 * This method is equivalent to the following code: 230 * <blockquote><pre>{@code 231 * MethodHandle getTarget, invoker, result; 232 * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class)); 233 * invoker = MethodHandles.exactInvoker(this.type()); 234 * result = MethodHandles.foldArguments(invoker, getTarget) 235 * }</pre></blockquote> 236 * 237 * @return a method handle which always invokes this call site's current target 238 */ 239 public abstract MethodHandle dynamicInvoker(); 240 241 /*non-public*/ MethodHandle makeDynamicInvoker() { 242 MethodHandle getTarget = GET_TARGET.bindArgumentL(0, this); 243 MethodHandle invoker = MethodHandles.exactInvoker(this.type()); 244 return MethodHandles.foldArguments(invoker, getTarget); 245 } 246 247 private static final MethodHandle GET_TARGET; 248 private static final MethodHandle THROW_UCS; 249 static { 250 try { 251 GET_TARGET = IMPL_LOOKUP. 252 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class)); 253 THROW_UCS = IMPL_LOOKUP. 254 findStatic(CallSite.class, "uninitializedCallSite", MethodType.methodType(Object.class, Object[].class)); 255 } catch (ReflectiveOperationException e) { 256 throw newInternalError(e); 257 } 258 } 259 260 /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */ 261 private static Object uninitializedCallSite(Object... ignore) { 262 throw new IllegalStateException("uninitialized call site"); 263 } 264 265 private MethodHandle makeUninitializedCallSite(MethodType targetType) { 266 MethodType basicType = targetType.basicType(); 267 MethodHandle invoker = basicType.form().cachedMethodHandle(MethodTypeForm.MH_UNINIT_CS); 268 if (invoker == null) { 269 invoker = THROW_UCS.asType(basicType); 270 invoker = basicType.form().setCachedMethodHandle(MethodTypeForm.MH_UNINIT_CS, invoker); 271 } 272 // unchecked view is OK since no values will be received or returned 273 return invoker.viewAsType(targetType, false); 274 } 275 276 // unsafe stuff: 277 private static final long TARGET_OFFSET; 278 private static final long CONTEXT_OFFSET; 279 static { 280 try { 281 TARGET_OFFSET = UNSAFE.objectFieldOffset(CallSite.class.getDeclaredField("target")); 282 CONTEXT_OFFSET = UNSAFE.objectFieldOffset(CallSite.class.getDeclaredField("context")); 283 } catch (Exception ex) { throw newInternalError(ex); } 284 } 285 286 /*package-private*/ 287 void setTargetNormal(MethodHandle newTarget) { 288 MethodHandleNatives.setCallSiteTargetNormal(this, newTarget); 289 } 290 /*package-private*/ 291 MethodHandle getTargetVolatile() { 292 return (MethodHandle) UNSAFE.getObjectVolatile(this, TARGET_OFFSET); 293 } 294 /*package-private*/ 295 void setTargetVolatile(MethodHandle newTarget) { 296 MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget); 297 } 298 299 // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite: 300 static CallSite makeSite(MethodHandle bootstrapMethod, 301 // Callee information: 302 String name, MethodType type, 303 // Extra arguments for BSM, if any: 304 Object info, 305 // Caller information: 306 Class<?> callerClass) { 307 MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass); 308 CallSite site; 309 try { 310 Object binding; 311 info = maybeReBox(info); 312 if (info == null) { 313 binding = bootstrapMethod.invoke(caller, name, type); 314 } else if (!info.getClass().isArray()) { 315 binding = bootstrapMethod.invoke(caller, name, type, info); 316 } else { 317 Object[] argv = (Object[]) info; 318 maybeReBoxElements(argv); 319 switch (argv.length) { 320 case 0: 321 binding = bootstrapMethod.invoke(caller, name, type); 322 break; 323 case 1: 324 binding = bootstrapMethod.invoke(caller, name, type, 325 argv[0]); 326 break; 327 case 2: 328 binding = bootstrapMethod.invoke(caller, name, type, 329 argv[0], argv[1]); 330 break; 331 case 3: 332 binding = bootstrapMethod.invoke(caller, name, type, 333 argv[0], argv[1], argv[2]); 334 break; 335 case 4: 336 binding = bootstrapMethod.invoke(caller, name, type, 337 argv[0], argv[1], argv[2], argv[3]); 338 break; 339 case 5: 340 binding = bootstrapMethod.invoke(caller, name, type, 341 argv[0], argv[1], argv[2], argv[3], argv[4]); 342 break; 343 case 6: 344 binding = bootstrapMethod.invoke(caller, name, type, 345 argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); 346 break; 347 default: 348 final int NON_SPREAD_ARG_COUNT = 3; // (caller, name, type) 349 if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY) 350 throw new BootstrapMethodError("too many bootstrap method arguments"); 351 MethodType bsmType = bootstrapMethod.type(); 352 MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length); 353 MethodHandle typedBSM = bootstrapMethod.asType(invocationType); 354 MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT); 355 binding = spreader.invokeExact(typedBSM, (Object)caller, (Object)name, (Object)type, argv); 356 } 357 } 358 //System.out.println("BSM for "+name+type+" => "+binding); 359 if (binding instanceof CallSite) { 360 site = (CallSite) binding; 361 } else { 362 throw new ClassCastException("bootstrap method failed to produce a CallSite"); 363 } 364 if (!site.getTarget().type().equals(type)) 365 throw wrongTargetType(site.getTarget(), type); 366 } catch (Throwable ex) { 367 BootstrapMethodError bex; 368 if (ex instanceof BootstrapMethodError) 369 bex = (BootstrapMethodError) ex; 370 else 371 bex = new BootstrapMethodError("call site initialization exception", ex); 372 throw bex; 373 } 374 return site; 375 } 376 377 private static Object maybeReBox(Object x) { 378 if (x instanceof Integer) { 379 int xi = (int) x; 380 if (xi == (byte) xi) 381 x = xi; // must rebox; see JLS 5.1.7 382 } 383 return x; 384 } 385 private static void maybeReBoxElements(Object[] xa) { 386 for (int i = 0; i < xa.length; i++) { 387 xa[i] = maybeReBox(xa[i]); 388 } 389 } 390 }