Path: blob/master/src/jdk.dynalink/share/classes/jdk/dynalink/DynamicLinker.java
41154 views
/*1* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file, and Oracle licenses the original version of this file under the BSD30* license:31*/32/*33Copyright 2009-2013 Attila Szegedi3435Redistribution and use in source and binary forms, with or without36modification, are permitted provided that the following conditions are37met:38* Redistributions of source code must retain the above copyright39notice, this list of conditions and the following disclaimer.40* Redistributions in binary form must reproduce the above copyright41notice, this list of conditions and the following disclaimer in the42documentation and/or other materials provided with the distribution.43* Neither the name of the copyright holder nor the names of44contributors may be used to endorse or promote products derived from45this software without specific prior written permission.4647THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS48IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED49TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A50PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER51BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR52CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF53SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR54BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,55WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR56OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF57ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.58*/5960package jdk.dynalink;6162import java.lang.StackWalker.StackFrame;63import java.lang.invoke.MethodHandle;64import java.lang.invoke.MethodHandles;65import java.lang.invoke.MethodType;66import java.lang.invoke.MutableCallSite;67import java.util.Objects;68import jdk.dynalink.linker.GuardedInvocation;69import jdk.dynalink.linker.GuardedInvocationTransformer;70import jdk.dynalink.linker.GuardingDynamicLinker;71import jdk.dynalink.linker.LinkRequest;72import jdk.dynalink.linker.LinkerServices;73import jdk.dynalink.linker.support.Lookup;74import jdk.dynalink.linker.support.SimpleLinkRequest;75import jdk.dynalink.support.ChainedCallSite;76import jdk.dynalink.support.SimpleRelinkableCallSite;7778/**79* The linker for {@link RelinkableCallSite} objects. A dynamic linker is a main80* objects when using Dynalink, it coordinates linking of call sites with81* linkers of available language runtimes that are represented by82* {@link GuardingDynamicLinker} objects (you only need to deal with these if83* you are yourself implementing a language runtime with its own object model84* and/or type conversions). To use Dynalink, you have to create one or more85* dynamic linkers using a {@link DynamicLinkerFactory}. Subsequently, you need86* to invoke its {@link #link(RelinkableCallSite)} method from87* {@code invokedynamic} bootstrap methods to let it manage all the call sites88* they create. Usual usage would be to create at least one class per language89* runtime to contain one linker instance as:90* <pre>91*92* class MyLanguageRuntime {93* private static final GuardingDynamicLinker myLanguageLinker = new MyLanguageLinker();94* private static final DynamicLinker dynamicLinker = createDynamicLinker();95*96* private static DynamicLinker createDynamicLinker() {97* final DynamicLinkerFactory factory = new DynamicLinkerFactory();98* factory.setPrioritizedLinker(myLanguageLinker);99* return factory.createLinker();100* }101*102* public static CallSite bootstrap(MethodHandles.Lookup lookup, String name, MethodType type) {103* return dynamicLinker.link(104* new SimpleRelinkableCallSite(105* new CallSiteDescriptor(lookup, parseOperation(name), type)));106* }107*108* private static Operation parseOperation(String name) {109* ...110* }111* }112* </pre>113* The above setup of one static linker instance is often too simple. You will114* often have your language runtime have a concept of some kind of115* "context class loader" and you will want to create one dynamic linker per116* such class loader, to ensure it incorporates linkers for all other language117* runtimes visible to that class loader (see118* {@link DynamicLinkerFactory#setClassLoader(ClassLoader)}).119* <p>120* There are three components you need to provide in the above example:121* <ul>122*123* <li>You are expected to provide a {@link GuardingDynamicLinker} for your own124* language. If your runtime doesn't have its own object model or type125* conversions, you don't need to implement a {@code GuardingDynamicLinker}; you126* would simply not invoke the {@code setPrioritizedLinker} method on the factory.</li>127*128* <li>The performance of the programs can depend on your choice of the class to129* represent call sites. The above example used130* {@link SimpleRelinkableCallSite}, but you might want to use131* {@link ChainedCallSite} instead. You'll need to experiment and decide what132* fits your runtime the best. You can further subclass either of these or133* implement your own.</li>134*135* <li>You also need to provide {@link CallSiteDescriptor}s to your call sites.136* They are immutable objects that contain all the information about the call137* site: the class performing the lookups, the operation being invoked, and the138* method signature. You will have to supply your own scheme to encode and139* decode operations in the call site name or static parameters, that is why140* in the above example the {@code parseOperation} method is left unimplemented.</li>141*142* </ul>143*/144public final class DynamicLinker {145private static final String CLASS_NAME = DynamicLinker.class.getName();146private static final String RELINK_METHOD_NAME = "relink";147148private static final String INITIAL_LINK_CLASS_NAME = "java.lang.invoke.MethodHandleNatives";149private static final String INITIAL_LINK_METHOD_NAME = "linkCallSite";150private static final String INVOKE_PACKAGE_PREFIX = "java.lang.invoke.";151152private static final StackWalker stackWalker = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES);153154private final LinkerServices linkerServices;155private final GuardedInvocationTransformer prelinkTransformer;156private final boolean syncOnRelink;157private final int unstableRelinkThreshold;158159/**160* Creates a new dynamic linker.161*162* @param linkerServices the linkerServices used by the linker, created by the factory.163* @param prelinkTransformer see {@link DynamicLinkerFactory#setPrelinkTransformer(GuardedInvocationTransformer)}164* @param syncOnRelink see {@link DynamicLinkerFactory#setSyncOnRelink(boolean)}165* @param unstableRelinkThreshold see {@link DynamicLinkerFactory#setUnstableRelinkThreshold(int)}166*/167DynamicLinker(final LinkerServices linkerServices, final GuardedInvocationTransformer prelinkTransformer,168final boolean syncOnRelink, final int unstableRelinkThreshold) {169if(unstableRelinkThreshold < 0) {170throw new IllegalArgumentException("unstableRelinkThreshold < 0");171}172this.linkerServices = linkerServices;173this.prelinkTransformer = prelinkTransformer;174this.syncOnRelink = syncOnRelink;175this.unstableRelinkThreshold = unstableRelinkThreshold;176}177178/**179* Links an invokedynamic call site. It will install a method handle into180* the call site that invokes the relinking mechanism of this linker. Next181* time the call site is invoked, it will be linked for the actual arguments182* it was invoked with.183*184* @param <T> the particular subclass of {@link RelinkableCallSite} for185* which to create a link.186* @param callSite the call site to link.187*188* @return the callSite, for easy call chaining.189*/190public <T extends RelinkableCallSite> T link(final T callSite) {191callSite.initialize(createRelinkAndInvokeMethod(callSite, 0));192return callSite;193}194195/**196* Returns the object representing the linker services of this class that197* are normally exposed to individual {@link GuardingDynamicLinker198* language-specific linkers}. While as a user of this class you normally199* only care about the {@link #link(RelinkableCallSite)} method, in certain200* circumstances you might want to use the lower level services directly;201* either to lookup specific method handles, to access the type converters,202* and so on.203*204* @return the object representing the linker services of this class.205*/206public LinkerServices getLinkerServices() {207return linkerServices;208}209210private static final MethodHandle RELINK = Lookup.findOwnSpecial(MethodHandles.lookup(), RELINK_METHOD_NAME,211MethodHandle.class, RelinkableCallSite.class, int.class, Object[].class);212213private MethodHandle createRelinkAndInvokeMethod(final RelinkableCallSite callSite, final int relinkCount) {214// Make a bound MH of invoke() for this linker and call site215final MethodHandle boundRelinker = MethodHandles.insertArguments(RELINK, 0, this, callSite, relinkCount);216// Make a MH that gathers all arguments to the invocation into an Object[]217final MethodType type = callSite.getDescriptor().getMethodType();218final MethodHandle collectingRelinker = boundRelinker.asCollector(Object[].class, type.parameterCount());219return MethodHandles.foldArguments(MethodHandles.exactInvoker(type), collectingRelinker.asType(220type.changeReturnType(MethodHandle.class)));221}222223/**224* Relinks a call site conforming to the invocation arguments.225*226* @param callSite the call site itself227* @param arguments arguments to the invocation228*229* @return return the method handle for the invocation230*231* @throws Exception rethrows any exception thrown by the linkers232*/233@SuppressWarnings("unused")234private MethodHandle relink(final RelinkableCallSite callSite, final int relinkCount, final Object... arguments) throws Exception {235final CallSiteDescriptor callSiteDescriptor = callSite.getDescriptor();236final boolean unstableDetectionEnabled = unstableRelinkThreshold > 0;237final boolean callSiteUnstable = unstableDetectionEnabled && relinkCount >= unstableRelinkThreshold;238final LinkRequest linkRequest = new SimpleLinkRequest(callSiteDescriptor, callSiteUnstable, arguments);239240GuardedInvocation guardedInvocation = linkerServices.getGuardedInvocation(linkRequest);241242// None found - throw an exception243if(guardedInvocation == null) {244throw new NoSuchDynamicMethodException(callSiteDescriptor.toString());245}246247// Make sure we transform the invocation before linking it into the call site. This is typically used to match the248// return type of the invocation to the call site.249guardedInvocation = prelinkTransformer.filter(guardedInvocation, linkRequest, linkerServices);250Objects.requireNonNull(guardedInvocation);251252int newRelinkCount = relinkCount;253// Note that the short-circuited "&&" evaluation below ensures we'll increment the relinkCount until254// threshold + 1 but not beyond that. Threshold + 1 is treated as a special value to signal that resetAndRelink255// has already executed once for the unstable call site; we only want the call site to throw away its current256// linkage once, when it transitions to unstable.257if(unstableDetectionEnabled && newRelinkCount <= unstableRelinkThreshold && newRelinkCount++ == unstableRelinkThreshold) {258callSite.resetAndRelink(guardedInvocation, createRelinkAndInvokeMethod(callSite, newRelinkCount));259} else {260callSite.relink(guardedInvocation, createRelinkAndInvokeMethod(callSite, newRelinkCount));261}262if(syncOnRelink) {263MutableCallSite.syncAll(new MutableCallSite[] { (MutableCallSite)callSite });264}265return guardedInvocation.getInvocation();266}267268/**269* Returns a stack trace element describing the location of the270* {@code invokedynamic} call site currently being linked on the current271* thread. The operation is potentially expensive as it needs to generate a272* stack trace to inspect it and is intended for use in diagnostics code.273* For "free-floating" call sites (not associated with an274* {@code invokedynamic} instruction), the result is not well-defined.275*276* @return a stack trace element describing the location of the call site277* currently being linked, or null if it is not invoked while a call278* site is being linked.279*/280public static StackTraceElement getLinkedCallSiteLocation() {281return stackWalker.walk(s -> s282// Find one of our linking entry points on the stack...283.dropWhile(f -> !(isRelinkFrame(f) || isInitialLinkFrame(f)))284.skip(1)285// ... then look for the first thing calling it that isn't j.l.invoke286.dropWhile(f -> f.getClassName().startsWith(INVOKE_PACKAGE_PREFIX))287.findFirst()288.map(StackFrame::toStackTraceElement)289.orElse(null)290);291}292293/**294* Returns {@code true} if the frame represents {@code MethodHandleNatives.linkCallSite()},295* the frame immediately on top of the call site frame when the call site is296* being linked for the first time.297*298* @param frame the frame299*300* @return {@code true} if this frame represents {@code MethodHandleNatives.linkCallSite()}.301*/302private static boolean isInitialLinkFrame(final StackFrame frame) {303return testFrame(frame, INITIAL_LINK_METHOD_NAME, INITIAL_LINK_CLASS_NAME);304}305306/**307* Returns {@code true} if the frame represents {@code DynamicLinker.relink()},308* the frame immediately on top of the call site frame when the call site is309* being relinked (linked for second and subsequent times).310*311* @param frame the frame312*313* @return {@code true} if this frame represents {@code DynamicLinker.relink()}.314*/315private static boolean isRelinkFrame(final StackFrame frame) {316return testFrame(frame, RELINK_METHOD_NAME, CLASS_NAME);317}318319private static boolean testFrame(final StackFrame frame, final String methodName, final String className) {320return methodName.equals(frame.getMethodName()) && className.equals(frame.getClassName());321}322}323324325