nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/Guards.java
changeset 33344 cc4a221f42b7
parent 33025 16b4968f9bb8
parent 33343 23abd10384a5
child 33345 ef8c859f7992
equal deleted inserted replaced
33025:16b4968f9bb8 33344:cc4a221f42b7
     1 /*
       
     2  * Copyright (c) 2010, 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 /*
       
    27  * This file is available under and governed by the GNU General Public
       
    28  * License version 2 only, as published by the Free Software Foundation.
       
    29  * However, the following notice accompanied the original version of this
       
    30  * file, and Oracle licenses the original version of this file under the BSD
       
    31  * license:
       
    32  */
       
    33 /*
       
    34    Copyright 2009-2013 Attila Szegedi
       
    35 
       
    36    Licensed under both the Apache License, Version 2.0 (the "Apache License")
       
    37    and the BSD License (the "BSD License"), with licensee being free to
       
    38    choose either of the two at their discretion.
       
    39 
       
    40    You may not use this file except in compliance with either the Apache
       
    41    License or the BSD License.
       
    42 
       
    43    If you choose to use this file in compliance with the Apache License, the
       
    44    following notice applies to you:
       
    45 
       
    46        You may obtain a copy of the Apache License at
       
    47 
       
    48            http://www.apache.org/licenses/LICENSE-2.0
       
    49 
       
    50        Unless required by applicable law or agreed to in writing, software
       
    51        distributed under the License is distributed on an "AS IS" BASIS,
       
    52        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
       
    53        implied. See the License for the specific language governing
       
    54        permissions and limitations under the License.
       
    55 
       
    56    If you choose to use this file in compliance with the BSD License, the
       
    57    following notice applies to you:
       
    58 
       
    59        Redistribution and use in source and binary forms, with or without
       
    60        modification, are permitted provided that the following conditions are
       
    61        met:
       
    62        * Redistributions of source code must retain the above copyright
       
    63          notice, this list of conditions and the following disclaimer.
       
    64        * Redistributions in binary form must reproduce the above copyright
       
    65          notice, this list of conditions and the following disclaimer in the
       
    66          documentation and/or other materials provided with the distribution.
       
    67        * Neither the name of the copyright holder nor the names of
       
    68          contributors may be used to endorse or promote products derived from
       
    69          this software without specific prior written permission.
       
    70 
       
    71        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
       
    72        IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
       
    73        TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
       
    74        PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
       
    75        BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
       
    76        CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
       
    77        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
       
    78        BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
       
    79        WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
       
    80        OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
       
    81        ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    82 */
       
    83 
       
    84 package jdk.internal.dynalink.support;
       
    85 
       
    86 import java.lang.invoke.MethodHandle;
       
    87 import java.lang.invoke.MethodHandles;
       
    88 import java.lang.invoke.MethodType;
       
    89 import java.util.logging.Level;
       
    90 import java.util.logging.Logger;
       
    91 import jdk.internal.dynalink.DynamicLinker;
       
    92 import jdk.internal.dynalink.linker.LinkerServices;
       
    93 
       
    94 /**
       
    95  * Utility methods for creating typical guards. TODO: introduce reasonable caching of created guards.
       
    96  *
       
    97  */
       
    98 public class Guards {
       
    99     private static final Logger LOG = Logger
       
   100             .getLogger(Guards.class.getName(), "jdk.internal.dynalink.support.messages");
       
   101 
       
   102     private Guards() {
       
   103     }
       
   104 
       
   105     /**
       
   106      * Creates a guard method handle with arguments of a specified type, but with boolean return value. When invoked, it
       
   107      * returns true if the first argument is of the specified class (exactly of it, not a subclass). The rest of the
       
   108      * arguments will be ignored.
       
   109      *
       
   110      * @param clazz the class of the first argument to test for
       
   111      * @param type the method type
       
   112      * @return a method handle testing whether its first argument is of the specified class.
       
   113      */
       
   114     @SuppressWarnings("boxing")
       
   115     public static MethodHandle isOfClass(final Class<?> clazz, final MethodType type) {
       
   116         final Class<?> declaredType = type.parameterType(0);
       
   117         if(clazz == declaredType) {
       
   118             LOG.log(Level.WARNING, "isOfClassGuardAlwaysTrue", new Object[] { clazz.getName(), 0, type, DynamicLinker.getLinkedCallSiteLocation() });
       
   119             return constantTrue(type);
       
   120         }
       
   121         if(!declaredType.isAssignableFrom(clazz)) {
       
   122             LOG.log(Level.WARNING, "isOfClassGuardAlwaysFalse", new Object[] { clazz.getName(), 0, type, DynamicLinker.getLinkedCallSiteLocation() });
       
   123             return constantFalse(type);
       
   124         }
       
   125         return getClassBoundArgumentTest(IS_OF_CLASS, clazz, 0, type);
       
   126     }
       
   127 
       
   128     /**
       
   129      * Creates a method handle with arguments of a specified type, but with boolean return value. When invoked, it
       
   130      * returns true if the first argument is instance of the specified class or its subclass). The rest of the arguments
       
   131      * will be ignored.
       
   132      *
       
   133      * @param clazz the class of the first argument to test for
       
   134      * @param type the method type
       
   135      * @return a method handle testing whether its first argument is of the specified class or subclass.
       
   136      */
       
   137     public static MethodHandle isInstance(final Class<?> clazz, final MethodType type) {
       
   138         return isInstance(clazz, 0, type);
       
   139     }
       
   140 
       
   141     /**
       
   142      * Creates a method handle with arguments of a specified type, but with boolean return value. When invoked, it
       
   143      * returns true if the n'th argument is instance of the specified class or its subclass). The rest of the arguments
       
   144      * will be ignored.
       
   145      *
       
   146      * @param clazz the class of the first argument to test for
       
   147      * @param pos the position on the argument list to test
       
   148      * @param type the method type
       
   149      * @return a method handle testing whether its first argument is of the specified class or subclass.
       
   150      */
       
   151     @SuppressWarnings("boxing")
       
   152     public static MethodHandle isInstance(final Class<?> clazz, final int pos, final MethodType type) {
       
   153         final Class<?> declaredType = type.parameterType(pos);
       
   154         if(clazz.isAssignableFrom(declaredType)) {
       
   155             LOG.log(Level.WARNING, "isInstanceGuardAlwaysTrue", new Object[] { clazz.getName(), pos, type, DynamicLinker.getLinkedCallSiteLocation() });
       
   156             return constantTrue(type);
       
   157         }
       
   158         if(!declaredType.isAssignableFrom(clazz)) {
       
   159             LOG.log(Level.WARNING, "isInstanceGuardAlwaysFalse", new Object[] { clazz.getName(), pos, type, DynamicLinker.getLinkedCallSiteLocation() });
       
   160             return constantFalse(type);
       
   161         }
       
   162         return getClassBoundArgumentTest(IS_INSTANCE, clazz, pos, type);
       
   163     }
       
   164 
       
   165     /**
       
   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 lit
       
   169      * @param type the method type of the handle
       
   170      * @return a method handle that returns true if the argument in the specified position is a Java array; the rest of
       
   171      * the arguments are ignored.
       
   172      */
       
   173     @SuppressWarnings("boxing")
       
   174     public static MethodHandle isArray(final int pos, final MethodType type) {
       
   175         final Class<?> declaredType = type.parameterType(pos);
       
   176         if(declaredType.isArray()) {
       
   177             LOG.log(Level.WARNING, "isArrayGuardAlwaysTrue", new Object[] { pos, type, DynamicLinker.getLinkedCallSiteLocation() });
       
   178             return constantTrue(type);
       
   179         }
       
   180         if(!declaredType.isAssignableFrom(Object[].class)) {
       
   181             LOG.log(Level.WARNING, "isArrayGuardAlwaysFalse", new Object[] { pos, type, DynamicLinker.getLinkedCallSiteLocation() });
       
   182             return constantFalse(type);
       
   183         }
       
   184         return asType(IS_ARRAY, pos, type);
       
   185     }
       
   186 
       
   187     /**
       
   188      * Return true if it is safe to strongly reference a class from the referred class loader from a class associated
       
   189      * with the referring class loader without risking a class loader memory leak.
       
   190      *
       
   191      * @param referrerLoader the referrer class loader
       
   192      * @param referredLoader the referred class loader
       
   193      * @return true if it is safe to strongly reference the class
       
   194      */
       
   195     public static boolean canReferenceDirectly(final ClassLoader referrerLoader, final ClassLoader referredLoader) {
       
   196         if(referredLoader == null) {
       
   197             // Can always refer directly to a system class
       
   198             return true;
       
   199         }
       
   200         if(referrerLoader == null) {
       
   201             // System classes can't refer directly to any non-system class
       
   202             return false;
       
   203         }
       
   204         // Otherwise, can only refer directly to classes residing in same or
       
   205         // parent class loader.
       
   206 
       
   207         ClassLoader referrer = referrerLoader;
       
   208         do {
       
   209             if(referrer == referredLoader) {
       
   210                 return true;
       
   211             }
       
   212             referrer = referrer.getParent();
       
   213         } while(referrer != null);
       
   214         return false;
       
   215     }
       
   216 
       
   217     private 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 test
       
   219         return asType(test.bindTo(clazz), pos, type);
       
   220     }
       
   221 
       
   222     /**
       
   223      * Takes a guard-test method handle, and adapts it to the requested type, returning a boolean. Only applies
       
   224      * conversions as per {@link MethodHandle#asType(MethodType)}.
       
   225      * @param test the test method handle
       
   226      * @param type the type to adapt the method handle to
       
   227      * @return the adapted method handle
       
   228      */
       
   229     public static MethodHandle asType(final MethodHandle test, final MethodType type) {
       
   230         return test.asType(getTestType(test, type));
       
   231     }
       
   232 
       
   233     /**
       
   234      * Takes a guard-test method handle, and adapts it to the requested type, returning a boolean. Applies the passed
       
   235      * {@link LinkerServices} object's {@link LinkerServices#asType(MethodHandle, MethodType)}.
       
   236      * @param linkerServices the linker services to use for type conversions
       
   237      * @param test the test method handle
       
   238      * @param type the type to adapt the method handle to
       
   239      * @return the adapted method handle
       
   240      */
       
   241     public static MethodHandle asType(final LinkerServices linkerServices, final MethodHandle test, final MethodType type) {
       
   242         return linkerServices.asType(test, getTestType(test, type));
       
   243     }
       
   244 
       
   245     private static MethodType getTestType(final MethodHandle test, final MethodType type) {
       
   246         return type.dropParameterTypes(test.type().parameterCount(),
       
   247                 type.parameterCount()).changeReturnType(boolean.class);
       
   248     }
       
   249 
       
   250     private static MethodHandle asType(final MethodHandle test, final int pos, final MethodType type) {
       
   251         assert test != null;
       
   252         assert type != null;
       
   253         assert type.parameterCount() > 0;
       
   254         assert pos >= 0 && pos < type.parameterCount();
       
   255         assert test.type().parameterCount() == 1;
       
   256         assert test.type().returnType() == Boolean.TYPE;
       
   257         return MethodHandles.permuteArguments(test.asType(test.type().changeParameterType(0, type.parameterType(pos))),
       
   258                 type.changeReturnType(Boolean.TYPE), new int[] { pos });
       
   259     }
       
   260 
       
   261     private static final MethodHandle IS_INSTANCE = Lookup.PUBLIC.findVirtual(Class.class, "isInstance",
       
   262             MethodType.methodType(Boolean.TYPE, Object.class));
       
   263 
       
   264     private static final MethodHandle IS_OF_CLASS;
       
   265     private static final MethodHandle IS_ARRAY;
       
   266     private static final MethodHandle IS_IDENTICAL;
       
   267     private static final MethodHandle IS_NULL;
       
   268     private static final MethodHandle IS_NOT_NULL;
       
   269 
       
   270     static {
       
   271         final Lookup lookup = new Lookup(MethodHandles.lookup());
       
   272 
       
   273         IS_OF_CLASS  = lookup.findOwnStatic("isOfClass",   Boolean.TYPE, Class.class, Object.class);
       
   274         IS_ARRAY     = lookup.findOwnStatic("isArray",     Boolean.TYPE, Object.class);
       
   275         IS_IDENTICAL = lookup.findOwnStatic("isIdentical", Boolean.TYPE, Object.class, Object.class);
       
   276         IS_NULL      = lookup.findOwnStatic("isNull",      Boolean.TYPE, Object.class);
       
   277         IS_NOT_NULL  = lookup.findOwnStatic("isNotNull",   Boolean.TYPE, Object.class);
       
   278     }
       
   279 
       
   280     /**
       
   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      */
       
   285     public static MethodHandle getClassGuard(final Class<?> clazz) {
       
   286         return IS_OF_CLASS.bindTo(clazz);
       
   287     }
       
   288 
       
   289     /**
       
   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      */
       
   294     public static MethodHandle getInstanceOfGuard(final Class<?> clazz) {
       
   295         return IS_INSTANCE.bindTo(clazz);
       
   296     }
       
   297 
       
   298     /**
       
   299      * Creates a guard method that tests its only argument for being referentially identical to another object
       
   300      * @param obj the object used as referential identity test
       
   301      * @return the desired guard method.
       
   302      */
       
   303     public static MethodHandle getIdentityGuard(final Object obj) {
       
   304         return IS_IDENTICAL.bindTo(obj);
       
   305     }
       
   306 
       
   307     /**
       
   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      */
       
   311     public static MethodHandle isNull() {
       
   312         return IS_NULL;
       
   313     }
       
   314 
       
   315     /**
       
   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      */
       
   319     public static MethodHandle isNotNull() {
       
   320         return IS_NOT_NULL;
       
   321     }
       
   322 
       
   323     @SuppressWarnings("unused")
       
   324     private static boolean isNull(final Object obj) {
       
   325         return obj == null;
       
   326     }
       
   327 
       
   328     @SuppressWarnings("unused")
       
   329     private static boolean isNotNull(final Object obj) {
       
   330         return obj != null;
       
   331     }
       
   332 
       
   333     @SuppressWarnings("unused")
       
   334     private static boolean isArray(final Object o) {
       
   335         return o != null && o.getClass().isArray();
       
   336     }
       
   337 
       
   338     @SuppressWarnings("unused")
       
   339     private static boolean isOfClass(final Class<?> c, final Object o) {
       
   340         return o != null && o.getClass() == c;
       
   341     }
       
   342 
       
   343     @SuppressWarnings("unused")
       
   344     private static boolean isIdentical(final Object o1, final Object o2) {
       
   345         return o1 == o2;
       
   346     }
       
   347 
       
   348     private static MethodHandle constantTrue(final MethodType type) {
       
   349         return constantBoolean(Boolean.TRUE, type);
       
   350     }
       
   351 
       
   352     private static MethodHandle constantFalse(final MethodType type) {
       
   353         return constantBoolean(Boolean.FALSE, type);
       
   354     }
       
   355 
       
   356     private static MethodHandle constantBoolean(final Boolean value, final MethodType type) {
       
   357         return MethodHandles.permuteArguments(MethodHandles.constant(Boolean.TYPE, value),
       
   358                 type.changeReturnType(Boolean.TYPE));
       
   359     }
       
   360 }