Path: blob/jdk8u272-b10-aarch32-20201026/nashorn/src/jdk/internal/dynalink/support/Guards.java
48797 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.support;8485import java.lang.invoke.MethodHandle;86import java.lang.invoke.MethodHandles;87import java.lang.invoke.MethodType;88import java.util.logging.Level;89import java.util.logging.Logger;90import jdk.internal.dynalink.DynamicLinker;91import jdk.internal.dynalink.linker.LinkerServices;9293/**94* Utility methods for creating typical guards. TODO: introduce reasonable caching of created guards.95*96* @author Attila Szegedi97*/98public class Guards {99private static final Logger LOG = Logger100.getLogger(Guards.class.getName(), "jdk.internal.dynalink.support.messages");101102private Guards() {103}104105/**106* Creates a guard method handle with arguments of a specified type, but with boolean return value. When invoked, it107* returns true if the first argument is of the specified class (exactly of it, not a subclass). The rest of the108* arguments will be ignored.109*110* @param clazz the class of the first argument to test for111* @param type the method type112* @return a method handle testing whether its first argument is of the specified class.113*/114@SuppressWarnings("boxing")115public static MethodHandle isOfClass(final Class<?> clazz, final MethodType type) {116final Class<?> declaredType = type.parameterType(0);117if(clazz == declaredType) {118LOG.log(Level.WARNING, "isOfClassGuardAlwaysTrue", new Object[] { clazz.getName(), 0, type, DynamicLinker.getLinkedCallSiteLocation() });119return constantTrue(type);120}121if(!declaredType.isAssignableFrom(clazz)) {122LOG.log(Level.WARNING, "isOfClassGuardAlwaysFalse", new Object[] { clazz.getName(), 0, type, DynamicLinker.getLinkedCallSiteLocation() });123return constantFalse(type);124}125return getClassBoundArgumentTest(IS_OF_CLASS, clazz, 0, type);126}127128/**129* Creates a method handle with arguments of a specified type, but with boolean return value. When invoked, it130* returns true if the first argument is instance of the specified class or its subclass). The rest of the arguments131* will be ignored.132*133* @param clazz the class of the first argument to test for134* @param type the method type135* @return a method handle testing whether its first argument is of the specified class or subclass.136*/137public static MethodHandle isInstance(final Class<?> clazz, final MethodType type) {138return isInstance(clazz, 0, type);139}140141/**142* Creates a method handle with arguments of a specified type, but with boolean return value. When invoked, it143* returns true if the n'th argument is instance of the specified class or its subclass). The rest of the arguments144* will be ignored.145*146* @param clazz the class of the first argument to test for147* @param pos the position on the argument list to test148* @param type the method type149* @return a method handle testing whether its first argument is of the specified class or subclass.150*/151@SuppressWarnings("boxing")152public static MethodHandle isInstance(final Class<?> clazz, final int pos, final MethodType type) {153final Class<?> declaredType = type.parameterType(pos);154if(clazz.isAssignableFrom(declaredType)) {155LOG.log(Level.WARNING, "isInstanceGuardAlwaysTrue", new Object[] { clazz.getName(), pos, type, DynamicLinker.getLinkedCallSiteLocation() });156return constantTrue(type);157}158if(!declaredType.isAssignableFrom(clazz)) {159LOG.log(Level.WARNING, "isInstanceGuardAlwaysFalse", new Object[] { clazz.getName(), pos, type, DynamicLinker.getLinkedCallSiteLocation() });160return constantFalse(type);161}162return getClassBoundArgumentTest(IS_INSTANCE, clazz, pos, type);163}164165/**166* Creates a method handle that returns true if the argument in the specified position is a Java array.167*168* @param pos the position in the argument lit169* @param type the method type of the handle170* @return a method handle that returns true if the argument in the specified position is a Java array; the rest of171* the arguments are ignored.172*/173@SuppressWarnings("boxing")174public static MethodHandle isArray(final int pos, final MethodType type) {175final Class<?> declaredType = type.parameterType(pos);176if(declaredType.isArray()) {177LOG.log(Level.WARNING, "isArrayGuardAlwaysTrue", new Object[] { pos, type, DynamicLinker.getLinkedCallSiteLocation() });178return constantTrue(type);179}180if(!declaredType.isAssignableFrom(Object[].class)) {181LOG.log(Level.WARNING, "isArrayGuardAlwaysFalse", new Object[] { pos, type, DynamicLinker.getLinkedCallSiteLocation() });182return constantFalse(type);183}184return asType(IS_ARRAY, pos, type);185}186187/**188* Return true if it is safe to strongly reference a class from the referred class loader from a class associated189* with the referring class loader without risking a class loader memory leak.190*191* @param referrerLoader the referrer class loader192* @param referredLoader the referred class loader193* @return true if it is safe to strongly reference the class194*/195public static boolean canReferenceDirectly(final ClassLoader referrerLoader, final ClassLoader referredLoader) {196if(referredLoader == null) {197// Can always refer directly to a system class198return true;199}200if(referrerLoader == null) {201// System classes can't refer directly to any non-system class202return false;203}204// Otherwise, can only refer directly to classes residing in same or205// parent class loader.206207ClassLoader referrer = referrerLoader;208do {209if(referrer == referredLoader) {210return true;211}212referrer = referrer.getParent();213} while(referrer != null);214return false;215}216217private static MethodHandle getClassBoundArgumentTest(final MethodHandle test, final Class<?> clazz, final int pos, final MethodType type) {218// Bind the class to the first argument of the test219return asType(test.bindTo(clazz), pos, type);220}221222/**223* Takes a guard-test method handle, and adapts it to the requested type, returning a boolean. Only applies224* conversions as per {@link MethodHandle#asType(MethodType)}.225* @param test the test method handle226* @param type the type to adapt the method handle to227* @return the adapted method handle228*/229public static MethodHandle asType(final MethodHandle test, final MethodType type) {230return test.asType(getTestType(test, type));231}232233/**234* Takes a guard-test method handle, and adapts it to the requested type, returning a boolean. Applies the passed235* {@link LinkerServices} object's {@link LinkerServices#asType(MethodHandle, MethodType)}.236* @param linkerServices the linker services to use for type conversions237* @param test the test method handle238* @param type the type to adapt the method handle to239* @return the adapted method handle240*/241public static MethodHandle asType(final LinkerServices linkerServices, final MethodHandle test, final MethodType type) {242return linkerServices.asType(test, getTestType(test, type));243}244245private static MethodType getTestType(final MethodHandle test, final MethodType type) {246return type.dropParameterTypes(test.type().parameterCount(),247type.parameterCount()).changeReturnType(boolean.class);248}249250private static MethodHandle asType(final MethodHandle test, final int pos, final MethodType type) {251assert test != null;252assert type != null;253assert type.parameterCount() > 0;254assert pos >= 0 && pos < type.parameterCount();255assert test.type().parameterCount() == 1;256assert test.type().returnType() == Boolean.TYPE;257return MethodHandles.permuteArguments(test.asType(test.type().changeParameterType(0, type.parameterType(pos))),258type.changeReturnType(Boolean.TYPE), new int[] { pos });259}260261private static final MethodHandle IS_INSTANCE = Lookup.PUBLIC.findVirtual(Class.class, "isInstance",262MethodType.methodType(Boolean.TYPE, Object.class));263264private static final MethodHandle IS_OF_CLASS;265private static final MethodHandle IS_ARRAY;266private static final MethodHandle IS_IDENTICAL;267private static final MethodHandle IS_NULL;268private static final MethodHandle IS_NOT_NULL;269270static {271final Lookup lookup = new Lookup(MethodHandles.lookup());272273IS_OF_CLASS = lookup.findOwnStatic("isOfClass", Boolean.TYPE, Class.class, Object.class);274IS_ARRAY = lookup.findOwnStatic("isArray", Boolean.TYPE, Object.class);275IS_IDENTICAL = lookup.findOwnStatic("isIdentical", Boolean.TYPE, Object.class, Object.class);276IS_NULL = lookup.findOwnStatic("isNull", Boolean.TYPE, Object.class);277IS_NOT_NULL = lookup.findOwnStatic("isNotNull", Boolean.TYPE, Object.class);278}279280/**281* Creates a guard method that tests its only argument for being of an exact particular class.282* @param clazz the class to test for.283* @return the desired guard method.284*/285public static MethodHandle getClassGuard(final Class<?> clazz) {286return IS_OF_CLASS.bindTo(clazz);287}288289/**290* Creates a guard method that tests its only argument for being an instance of a particular class.291* @param clazz the class to test for.292* @return the desired guard method.293*/294public static MethodHandle getInstanceOfGuard(final Class<?> clazz) {295return IS_INSTANCE.bindTo(clazz);296}297298/**299* Creates a guard method that tests its only argument for being referentially identical to another object300* @param obj the object used as referential identity test301* @return the desired guard method.302*/303public static MethodHandle getIdentityGuard(final Object obj) {304return IS_IDENTICAL.bindTo(obj);305}306307/**308* Returns a guard that tests whether the first argument is null.309* @return a guard that tests whether the first argument is null.310*/311public static MethodHandle isNull() {312return IS_NULL;313}314315/**316* Returns a guard that tests whether the first argument is not null.317* @return a guard that tests whether the first argument is not null.318*/319public static MethodHandle isNotNull() {320return IS_NOT_NULL;321}322323@SuppressWarnings("unused")324private static boolean isNull(final Object obj) {325return obj == null;326}327328@SuppressWarnings("unused")329private static boolean isNotNull(final Object obj) {330return obj != null;331}332333@SuppressWarnings("unused")334private static boolean isArray(final Object o) {335return o != null && o.getClass().isArray();336}337338@SuppressWarnings("unused")339private static boolean isOfClass(final Class<?> c, final Object o) {340return o != null && o.getClass() == c;341}342343@SuppressWarnings("unused")344private static boolean isIdentical(final Object o1, final Object o2) {345return o1 == o2;346}347348private static MethodHandle constantTrue(final MethodType type) {349return constantBoolean(Boolean.TRUE, type);350}351352private static MethodHandle constantFalse(final MethodType type) {353return constantBoolean(Boolean.FALSE, type);354}355356private static MethodHandle constantBoolean(final Boolean value, final MethodType type) {357return MethodHandles.permuteArguments(MethodHandles.constant(Boolean.TYPE, value),358type.changeReturnType(Boolean.TYPE));359}360}361362363