Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/src/jdk/internal/dynalink/DynamicLinkerFactory.java
48600 views
/*1* Copyright (c) 2010, 2013, 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 Szegedi3435Licensed under both the Apache License, Version 2.0 (the "Apache License")36and the BSD License (the "BSD License"), with licensee being free to37choose either of the two at their discretion.3839You may not use this file except in compliance with either the Apache40License or the BSD License.4142If you choose to use this file in compliance with the Apache License, the43following notice applies to you:4445You may obtain a copy of the Apache License at4647http://www.apache.org/licenses/LICENSE-2.04849Unless required by applicable law or agreed to in writing, software50distributed under the License is distributed on an "AS IS" BASIS,51WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or52implied. See the License for the specific language governing53permissions and limitations under the License.5455If you choose to use this file in compliance with the BSD License, the56following notice applies to you:5758Redistribution and use in source and binary forms, with or without59modification, are permitted provided that the following conditions are60met:61* Redistributions of source code must retain the above copyright62notice, this list of conditions and the following disclaimer.63* Redistributions in binary form must reproduce the above copyright64notice, this list of conditions and the following disclaimer in the65documentation and/or other materials provided with the distribution.66* Neither the name of the copyright holder nor the names of67contributors may be used to endorse or promote products derived from68this software without specific prior written permission.6970THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS71IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED72TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A73PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER74BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR75CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF76SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR77BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,78WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR79OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF80ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.81*/8283package jdk.internal.dynalink;8485import java.lang.invoke.MutableCallSite;86import java.security.AccessController;87import java.security.PrivilegedAction;88import java.util.ArrayList;89import java.util.Arrays;90import java.util.Collections;91import java.util.HashSet;92import java.util.LinkedList;93import java.util.List;94import java.util.Set;95import jdk.internal.dynalink.beans.BeansLinker;96import jdk.internal.dynalink.linker.GuardingDynamicLinker;97import jdk.internal.dynalink.linker.GuardingTypeConverterFactory;98import jdk.internal.dynalink.linker.LinkRequest;99import jdk.internal.dynalink.linker.LinkerServices;100import jdk.internal.dynalink.linker.MethodHandleTransformer;101import jdk.internal.dynalink.linker.MethodTypeConversionStrategy;102import jdk.internal.dynalink.support.AutoDiscovery;103import jdk.internal.dynalink.support.BottomGuardingDynamicLinker;104import jdk.internal.dynalink.support.ClassLoaderGetterContextProvider;105import jdk.internal.dynalink.support.CompositeGuardingDynamicLinker;106import jdk.internal.dynalink.support.CompositeTypeBasedGuardingDynamicLinker;107import jdk.internal.dynalink.support.DefaultPrelinkFilter;108import jdk.internal.dynalink.support.LinkerServicesImpl;109import jdk.internal.dynalink.support.TypeConverterFactory;110import jdk.internal.dynalink.support.TypeUtilities;111112/**113* A factory class for creating {@link DynamicLinker}s. The most usual dynamic linker is a linker that is a composition114* of all {@link GuardingDynamicLinker}s known and pre-created by the caller as well as any115* {@link AutoDiscovery automatically discovered} guarding linkers and the standard fallback {@link BeansLinker} and a116* {@link DefaultPrelinkFilter}. See {@link DynamicLinker} documentation for tips on how to use this class.117*118* @author Attila Szegedi119*/120public class DynamicLinkerFactory {121/**122* Default value for {@link #setUnstableRelinkThreshold(int) unstable relink threshold}.123*/124public static final int DEFAULT_UNSTABLE_RELINK_THRESHOLD = 8;125126private boolean classLoaderExplicitlySet = false;127private ClassLoader classLoader;128129private List<? extends GuardingDynamicLinker> prioritizedLinkers;130private List<? extends GuardingDynamicLinker> fallbackLinkers;131private int runtimeContextArgCount = 0;132private boolean syncOnRelink = false;133private int unstableRelinkThreshold = DEFAULT_UNSTABLE_RELINK_THRESHOLD;134private GuardedInvocationFilter prelinkFilter;135private MethodTypeConversionStrategy autoConversionStrategy;136private MethodHandleTransformer internalObjectsFilter;137138/**139* Sets the class loader for automatic discovery of available linkers. If not set explicitly, then the thread140* context class loader at the time of {@link #createLinker()} invocation will be used.141*142* @param classLoader the class loader used for the autodiscovery of available linkers.143*/144public void setClassLoader(final ClassLoader classLoader) {145this.classLoader = classLoader;146classLoaderExplicitlySet = true;147}148149/**150* Sets the prioritized linkers. Language runtimes using this framework will usually precreate at least the linker151* for their own language. These linkers will be consulted first in the resulting dynamic linker, before any152* autodiscovered linkers. If the framework also autodiscovers a linker of the same class as one of the prioritized153* linkers, it will be ignored and the explicit prioritized instance will be used.154*155* @param prioritizedLinkers the list of prioritized linkers. Null can be passed to indicate no prioritized linkers156* (this is also the default value).157*/158public void setPrioritizedLinkers(final List<? extends GuardingDynamicLinker> prioritizedLinkers) {159this.prioritizedLinkers =160prioritizedLinkers == null ? null : new ArrayList<>(prioritizedLinkers);161}162163/**164* Sets the prioritized linkers. Language runtimes using this framework will usually precreate at least the linker165* for their own language. These linkers will be consulted first in the resulting dynamic linker, before any166* autodiscovered linkers. If the framework also autodiscovers a linker of the same class as one of the prioritized167* linkers, it will be ignored and the explicit prioritized instance will be used.168*169* @param prioritizedLinkers a list of prioritized linkers.170*/171public void setPrioritizedLinkers(final GuardingDynamicLinker... prioritizedLinkers) {172setPrioritizedLinkers(Arrays.asList(prioritizedLinkers));173}174175/**176* Sets a single prioritized linker. Identical to calling {@link #setPrioritizedLinkers(List)} with a single-element177* list.178*179* @param prioritizedLinker the single prioritized linker. Must not be null.180* @throws IllegalArgumentException if null is passed.181*/182public void setPrioritizedLinker(final GuardingDynamicLinker prioritizedLinker) {183if(prioritizedLinker == null) {184throw new IllegalArgumentException("prioritizedLinker == null");185}186this.prioritizedLinkers = Collections.singletonList(prioritizedLinker);187}188189/**190* Sets the fallback linkers. These linkers will be consulted last in the resulting composite linker, after any191* autodiscovered linkers. If the framework also autodiscovers a linker of the same class as one of the fallback192* linkers, it will be ignored and the explicit fallback instance will be used.193*194* @param fallbackLinkers the list of fallback linkers. Can be empty to indicate the caller wishes to set no195* fallback linkers.196*/197public void setFallbackLinkers(final List<? extends GuardingDynamicLinker> fallbackLinkers) {198this.fallbackLinkers = fallbackLinkers == null ? null : new ArrayList<>(fallbackLinkers);199}200201/**202* Sets the fallback linkers. These linkers will be consulted last in the resulting composite linker, after any203* autodiscovered linkers. If the framework also autodiscovers a linker of the same class as one of the fallback204* linkers, it will be ignored and the explicit fallback instance will be used.205*206* @param fallbackLinkers the list of fallback linkers. Can be empty to indicate the caller wishes to set no207* fallback linkers. If it is left as null, the standard fallback {@link BeansLinker} will be used.208*/209public void setFallbackLinkers(final GuardingDynamicLinker... fallbackLinkers) {210setFallbackLinkers(Arrays.asList(fallbackLinkers));211}212213/**214* Sets the number of arguments in the call sites that represent the stack context of the language runtime creating215* the linker. If the language runtime uses no context information passed on stack, then it should be zero216* (the default value). If it is set to nonzero value, then every dynamic call site emitted by this runtime must217* have the argument list of the form: {@code (this, contextArg1[, contextArg2[, ...]], normalArgs)}. It is218* advisable to only pass one context-specific argument, though, of an easily recognizable, runtime specific type219* encapsulating the runtime thread local state.220*221* @param runtimeContextArgCount the number of language runtime context arguments in call sites.222*/223public void setRuntimeContextArgCount(final int runtimeContextArgCount) {224if(runtimeContextArgCount < 0) {225throw new IllegalArgumentException("runtimeContextArgCount < 0");226}227this.runtimeContextArgCount = runtimeContextArgCount;228}229230/**231* Sets whether the linker created by this factory will invoke {@link MutableCallSite#syncAll(MutableCallSite[])}232* after a call site is relinked. Defaults to false. You probably want to set it to true if your runtime supports233* multithreaded execution of dynamically linked code.234* @param syncOnRelink true for invoking sync on relink, false otherwise.235*/236public void setSyncOnRelink(final boolean syncOnRelink) {237this.syncOnRelink = syncOnRelink;238}239240/**241* Sets the unstable relink threshold; the number of times a call site is relinked after which it will be242* considered unstable, and subsequent link requests for it will indicate this.243* @param unstableRelinkThreshold the new threshold. Must not be less than zero. The value of zero means that244* call sites will never be considered unstable.245* @see LinkRequest#isCallSiteUnstable()246*/247public void setUnstableRelinkThreshold(final int unstableRelinkThreshold) {248if(unstableRelinkThreshold < 0) {249throw new IllegalArgumentException("unstableRelinkThreshold < 0");250}251this.unstableRelinkThreshold = unstableRelinkThreshold;252}253254/**255* Set the pre-link filter. This is a {@link GuardedInvocationFilter} that will get the final chance to modify the256* guarded invocation after it has been created by a component linker and before the dynamic linker links it into257* the call site. It is normally used to adapt the return value type of the invocation to the type of the call site.258* When not set explicitly, {@link DefaultPrelinkFilter} will be used.259* @param prelinkFilter the pre-link filter for the dynamic linker.260*/261public void setPrelinkFilter(final GuardedInvocationFilter prelinkFilter) {262this.prelinkFilter = prelinkFilter;263}264265/**266* Sets an object representing the conversion strategy for automatic type conversions. After267* {@link TypeConverterFactory#asType(java.lang.invoke.MethodHandle, java.lang.invoke.MethodType)} has268* applied all custom conversions to a method handle, it still needs to effect269* {@link TypeUtilities#isMethodInvocationConvertible(Class, Class) method invocation conversions} that270* can usually be automatically applied as per271* {@link java.lang.invoke.MethodHandle#asType(java.lang.invoke.MethodType)}.272* However, sometimes language runtimes will want to customize even those conversions for their own call273* sites. A typical example is allowing unboxing of null return values, which is by default prohibited by274* ordinary {@code MethodHandles.asType}. In this case, a language runtime can install its own custom275* automatic conversion strategy, that can deal with null values. Note that when the strategy's276* {@link MethodTypeConversionStrategy#asType(java.lang.invoke.MethodHandle, java.lang.invoke.MethodType)}277* is invoked, the custom language conversions will already have been applied to the method handle, so by278* design the difference between the handle's current method type and the desired final type will always279* only be ones that can be subjected to method invocation conversions. The strategy also doesn't need to280* invoke a final {@code MethodHandle.asType()} as the converter factory will do that as the final step.281* @param autoConversionStrategy the strategy for applying method invocation conversions for the linker282* created by this factory.283*/284public void setAutoConversionStrategy(final MethodTypeConversionStrategy autoConversionStrategy) {285this.autoConversionStrategy = autoConversionStrategy;286}287288/**289* Sets a method handle transformer that is supposed to act as the implementation of this linker factory's linkers'290* services {@link LinkerServices#filterInternalObjects(java.lang.invoke.MethodHandle)} method.291* @param internalObjectsFilter a method handle transformer filtering out internal objects, or null.292*/293public void setInternalObjectsFilter(final MethodHandleTransformer internalObjectsFilter) {294this.internalObjectsFilter = internalObjectsFilter;295}296297/**298* Creates a new dynamic linker consisting of all the prioritized, autodiscovered, and fallback linkers as well as299* the pre-link filter.300*301* @return the new dynamic Linker302*/303public DynamicLinker createLinker() {304// Treat nulls appropriately305if(prioritizedLinkers == null) {306prioritizedLinkers = Collections.emptyList();307}308if(fallbackLinkers == null) {309fallbackLinkers = Collections.singletonList(new BeansLinker());310}311312// Gather classes of all precreated (prioritized and fallback) linkers.313// We'll filter out any discovered linkers of the same class.314final Set<Class<? extends GuardingDynamicLinker>> knownLinkerClasses =315new HashSet<>();316addClasses(knownLinkerClasses, prioritizedLinkers);317addClasses(knownLinkerClasses, fallbackLinkers);318319final ClassLoader effectiveClassLoader = classLoaderExplicitlySet ? classLoader : getThreadContextClassLoader();320final List<GuardingDynamicLinker> discovered = AutoDiscovery.loadLinkers(effectiveClassLoader);321// Now, concatenate ...322final List<GuardingDynamicLinker> linkers =323new ArrayList<>(prioritizedLinkers.size() + discovered.size()324+ fallbackLinkers.size());325// ... prioritized linkers, ...326linkers.addAll(prioritizedLinkers);327// ... filtered discovered linkers, ...328for(final GuardingDynamicLinker linker: discovered) {329if(!knownLinkerClasses.contains(linker.getClass())) {330linkers.add(linker);331}332}333// ... and finally fallback linkers.334linkers.addAll(fallbackLinkers);335final List<GuardingDynamicLinker> optimized = CompositeTypeBasedGuardingDynamicLinker.optimize(linkers);336final GuardingDynamicLinker composite;337switch(linkers.size()) {338case 0: {339composite = BottomGuardingDynamicLinker.INSTANCE;340break;341}342case 1: {343composite = optimized.get(0);344break;345}346default: {347composite = new CompositeGuardingDynamicLinker(optimized);348break;349}350}351352final List<GuardingTypeConverterFactory> typeConverters = new LinkedList<>();353for(final GuardingDynamicLinker linker: linkers) {354if(linker instanceof GuardingTypeConverterFactory) {355typeConverters.add((GuardingTypeConverterFactory)linker);356}357}358359if(prelinkFilter == null) {360prelinkFilter = new DefaultPrelinkFilter();361}362363return new DynamicLinker(new LinkerServicesImpl(new TypeConverterFactory(typeConverters,364autoConversionStrategy), composite, internalObjectsFilter), prelinkFilter, runtimeContextArgCount,365syncOnRelink, unstableRelinkThreshold);366}367368private static ClassLoader getThreadContextClassLoader() {369return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {370@Override371public ClassLoader run() {372return Thread.currentThread().getContextClassLoader();373}374}, ClassLoaderGetterContextProvider.GET_CLASS_LOADER_CONTEXT);375}376377private static void addClasses(final Set<Class<? extends GuardingDynamicLinker>> knownLinkerClasses,378final List<? extends GuardingDynamicLinker> linkers) {379for(final GuardingDynamicLinker linker: linkers) {380knownLinkerClasses.add(linker.getClass());381}382}383}384385386