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.linker;
  85 
  86 import static jdk.nashorn.internal.lookup.Lookup.MH;
  87 
  88 import java.lang.invoke.MethodHandle;
  89 import java.lang.invoke.MethodHandles;
  90 import java.lang.invoke.MethodType;
  91 import java.lang.invoke.SwitchPoint;
  92 import java.lang.invoke.WrongMethodTypeException;
  93 import java.util.List;
  94 import jdk.internal.dynalink.CallSiteDescriptor;
  95 import jdk.internal.dynalink.support.Guards;
  96 
  97 /**
  98  * Represents a conditionally valid method handle. It is an immutable triple of an invocation method handle, a guard
  99  * method handle that defines the applicability of the invocation handle, and a switch point that can be used for
 100  * external invalidation of the invocation handle. The invocation handle is suitable for invocation if the guard
 101  * handle returns true for its arguments, and as long as the switch point is not invalidated. Both the guard and the
 102  * switch point are optional; neither, one, or both can be present.
 103  *
 104  * @author Attila Szegedi
 105  */
 106 public class GuardedInvocation {
 107     private final MethodHandle invocation;
 108     private final MethodHandle guard;
 109     private final Class<? extends Throwable> exception;
 110     private final SwitchPoint[] switchPoints;
 111 
 112     /**
 113      * Creates a new guarded invocation. This invocation is unconditional as it has no invalidations.
 114      *
 115      * @param invocation the method handle representing the invocation. Must not be null.
 116      * @throws NullPointerException if invocation is null.
 117      */
 118     public GuardedInvocation(final MethodHandle invocation) {
 119         this(invocation, null, (SwitchPoint)null, null);
 120     }
 121 
 122     /**
 123      * Creates a new guarded invocation.
 124      *
 125      * @param invocation the method handle representing the invocation. Must not be null.
 126      * @param guard the method handle representing the guard. Must have the same method type as the invocation, except
 127      * it must return boolean. For some useful guards, check out the {@link Guards} class. It can be null to represent
 128      * an unconditional invocation, although that is unusual.
 129      * @throws NullPointerException if invocation is null.
 130      */
 131     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard) {
 132         this(invocation, guard, (SwitchPoint)null, null);
 133     }
 134 
 135     /**
 136      * Creates a new guarded invocation.
 137      *
 138      * @param invocation the method handle representing the invocation. Must not be null.
 139      * @param switchPoint the optional switch point that can be used to invalidate this linkage.
 140      * @throws NullPointerException if invocation is null.
 141      */
 142     public GuardedInvocation(final MethodHandle invocation, final SwitchPoint switchPoint) {
 143         this(invocation, null, switchPoint, null);
 144     }
 145 
 146     /**
 147      * Creates a new guarded invocation.
 148      *
 149      * @param invocation the method handle representing the invocation. Must not be null.
 150      * @param guard the method handle representing the guard. Must have the same method type as the invocation, except
 151      * it must return boolean. For some useful guards, check out the {@link Guards} class. It can be null. If both it
 152      * and the switch point are null, this represents an unconditional invocation, which is legal but unusual.
 153      * @param switchPoint the optional switch point that can be used to invalidate this linkage.
 154      * @throws NullPointerException if invocation is null.
 155      */
 156     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint switchPoint) {
 157         this(invocation, guard, switchPoint, null);
 158     }
 159 
 160     /**
 161      * Creates a new guarded invocation.
 162      *
 163      * @param invocation the method handle representing the invocation. Must not be null.
 164      * @param guard the method handle representing the guard. Must have the same method type as the invocation, except
 165      * it must return boolean. For some useful guards, check out the {@link Guards} class. It can be null. If both it
 166      * and the switch point are null, this represents an unconditional invocation, which is legal but unusual.
 167      * @param switchPoint the optional switch point that can be used to invalidate this linkage.
 168      * @param exception the optional exception type that is expected to be thrown by the invocation and that also
 169      * invalidates the linkage.
 170      * @throws NullPointerException if invocation is null.
 171      */
 172     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint switchPoint, final Class<? extends Throwable> exception) {
 173         invocation.getClass(); // NPE check
 174         this.invocation = invocation;
 175         this.guard = guard;
 176         this.switchPoints = switchPoint == null ? null : new SwitchPoint[] { switchPoint };
 177         this.exception = exception;
 178     }
 179 
 180     /**
 181      * Creates a new guarded invocation
 182      *
 183      * @param invocation the method handle representing the invocation. Must not be null.
 184      * @param guard the method handle representing the guard. Must have the same method type as the invocation, except
 185      * it must return boolean. For some useful guards, check out the {@link Guards} class. It can be null. If both it
 186      * and the switch point are null, this represents an unconditional invocation, which is legal but unusual.
 187      * @param switchPoints the optional switch points that can be used to invalidate this linkage.
 188      * @param exception the optional exception type that is expected to be thrown by the invocation and that also
 189      * invalidates the linkage.
 190      * @throws NullPointerException if invocation is null.
 191      */
 192     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint[] switchPoints, final Class<? extends Throwable> exception) {
 193         invocation.getClass(); // NPE check
 194         this.invocation = invocation;
 195         this.guard = guard;
 196         this.switchPoints = switchPoints == null ? null : switchPoints.clone();
 197         this.exception = exception;
 198     }
 199 
 200     /**
 201      * Returns the invocation method handle.
 202      *
 203      * @return the invocation method handle. It will never be null.
 204      */
 205     public MethodHandle getInvocation() {
 206         return invocation;
 207     }
 208 
 209     /**
 210      * Returns the guard method handle.
 211      *
 212      * @return the guard method handle. Can be null.
 213      */
 214     public MethodHandle getGuard() {
 215         return guard;
 216     }
 217 
 218     /**
 219      * Returns the switch point that can be used to invalidate the invocation handle.
 220      *
 221      * @return the switch point that can be used to invalidate the invocation handle. Can be null.
 222      */
 223     public SwitchPoint[] getSwitchPoints() {
 224         return switchPoints == null ? null : switchPoints.clone();
 225     }
 226 
 227     /**
 228      * Returns the exception type that if thrown should be used to invalidate the linkage.
 229      *
 230      * @return the exception type that if thrown should be used to invalidate the linkage. Can be null.
 231      */
 232     public Class<? extends Throwable> getException() {
 233         return exception;
 234     }
 235 
 236     /**
 237      * Returns true if and only if this guarded invocation has a switchpoint, and that switchpoint has been invalidated.
 238      * @return true if and only if this guarded invocation has a switchpoint, and that switchpoint has been invalidated.
 239      */
 240     public boolean hasBeenInvalidated() {
 241         if (switchPoints == null) {
 242             return false;
 243         }
 244         for (final SwitchPoint sp : switchPoints) {
 245             if (sp.hasBeenInvalidated()) {
 246                 return true;
 247             }
 248         }
 249         return false;
 250     }
 251 
 252     /**
 253      * Asserts that the invocation is of the specified type, and the guard (if present) is of the specified type with a
 254      * boolean return type.
 255      *
 256      * @param type the asserted type
 257      * @throws WrongMethodTypeException if the invocation and the guard are not of the expected method type.
 258      */
 259     public void assertType(final MethodType type) {
 260         assertType(invocation, type);
 261         if (guard != null) {
 262             assertType(guard, type.changeReturnType(Boolean.TYPE));
 263         }
 264     }
 265 
 266     /**
 267      * Creates a new guarded invocation with different methods, preserving the switch point.
 268      *
 269      * @param newInvocation the new invocation
 270      * @param newGuard the new guard
 271      * @return a new guarded invocation with the replaced methods and the same switch point as this invocation.
 272      */
 273     public GuardedInvocation replaceMethods(final MethodHandle newInvocation, final MethodHandle newGuard) {
 274         return new GuardedInvocation(newInvocation, newGuard, switchPoints, exception);
 275     }
 276 
 277     /**
 278      * Add a switchpoint to this guarded invocation
 279      * @param newSwitchPoint new switchpoint, or null for nop
 280      * @return new guarded invocation with the extra switchpoint
 281      */
 282     public GuardedInvocation addSwitchPoint(final SwitchPoint newSwitchPoint) {
 283         if (newSwitchPoint == null) {
 284             return this;
 285         }
 286 
 287         final SwitchPoint[] newSwitchPoints;
 288         if (switchPoints != null) {
 289             newSwitchPoints = new SwitchPoint[switchPoints.length + 1];
 290             System.arraycopy(switchPoints, 0, newSwitchPoints, 0, switchPoints.length);
 291             newSwitchPoints[switchPoints.length] = newSwitchPoint;
 292         } else {
 293             newSwitchPoints = new SwitchPoint[] { newSwitchPoint };
 294         }
 295 
 296         return new GuardedInvocation(invocation, guard, newSwitchPoints, exception);
 297     }
 298 
 299     private GuardedInvocation replaceMethodsOrThis(final MethodHandle newInvocation, final MethodHandle newGuard) {
 300         if (newInvocation == invocation && newGuard == guard) {
 301             return this;
 302         }
 303         return replaceMethods(newInvocation, newGuard);
 304     }
 305 
 306     /**
 307      * Changes the type of the invocation, as if {@link MethodHandle#asType(MethodType)} was applied to its invocation
 308      * and its guard, if it has one (with return type changed to boolean, and parameter count potentially truncated for
 309      * the guard). If the invocation already is of the required type, returns this object.
 310      * @param newType the new type of the invocation.
 311      * @return a guarded invocation with the new type applied to it.
 312      */
 313     public GuardedInvocation asType(final MethodType newType) {
 314         return replaceMethodsOrThis(invocation.asType(newType), guard == null ? null : Guards.asType(guard, newType));
 315     }
 316 
 317     /**
 318      * Changes the type of the invocation, as if {@link LinkerServices#asType(MethodHandle, MethodType)} was applied to
 319      * its invocation and its guard, if it has one (with return type changed to boolean, and parameter count potentially
 320      * truncated for the guard). If the invocation already is of the required type, returns this object.
 321      * @param linkerServices the linker services to use for the conversion
 322      * @param newType the new type of the invocation.
 323      * @return a guarded invocation with the new type applied to it.
 324      */
 325     public GuardedInvocation asType(final LinkerServices linkerServices, final MethodType newType) {
 326         return replaceMethodsOrThis(linkerServices.asType(invocation, newType), guard == null ? null :
 327             Guards.asType(linkerServices, guard, newType));
 328     }
 329 
 330     /**
 331      * Changes the type of the invocation, as if {@link LinkerServices#asTypeLosslessReturn(MethodHandle, MethodType)} was
 332      * applied to its invocation and {@link LinkerServices#asType(MethodHandle, MethodType)} applied to its guard, if it
 333      * has one (with return type changed to boolean, and parameter count potentially truncated for the guard). If the
 334      * invocation doesn't change its type, returns this object.
 335      * @param linkerServices the linker services to use for the conversion
 336      * @param newType the new type of the invocation.
 337      * @return a guarded invocation with the new type applied to it.
 338      */
 339     public GuardedInvocation asTypeSafeReturn(final LinkerServices linkerServices, final MethodType newType) {
 340         return replaceMethodsOrThis(linkerServices.asTypeLosslessReturn(invocation, newType), guard == null ? null :
 341             Guards.asType(linkerServices, guard, newType));
 342     }
 343 
 344     /**
 345      * Changes the type of the invocation, as if {@link MethodHandle#asType(MethodType)} was applied to its invocation
 346      * and its guard, if it has one (with return type changed to boolean for guard). If the invocation already is of the
 347      * required type, returns this object.
 348      * @param desc a call descriptor whose method type is adapted.
 349      * @return a guarded invocation with the new type applied to it.
 350      */
 351     public GuardedInvocation asType(final CallSiteDescriptor desc) {
 352         return asType(desc.getMethodType());
 353     }
 354 
 355     /**
 356      * Applies argument filters to both the invocation and the guard (if there is one).
 357      * @param pos the position of the first argumen being filtered
 358      * @param filters the argument filters
 359      * @return a filtered invocation
 360      */
 361     public GuardedInvocation filterArguments(final int pos, final MethodHandle... filters) {
 362         return replaceMethods(MethodHandles.filterArguments(invocation, pos, filters), guard == null ? null :
 363             MethodHandles.filterArguments(guard, pos, filters));
 364     }
 365 
 366     /**
 367      * Makes an invocation that drops arguments in both the invocation and the guard (if there is one).
 368      * @param pos the position of the first argument being dropped
 369      * @param valueTypes the types of the values being dropped
 370      * @return an invocation that drops arguments
 371      */
 372     public GuardedInvocation dropArguments(final int pos, final List<Class<?>> valueTypes) {
 373         return replaceMethods(MethodHandles.dropArguments(invocation, pos, valueTypes), guard == null ? null :
 374             MethodHandles.dropArguments(guard, pos, valueTypes));
 375     }
 376 
 377     /**
 378      * Makes an invocation that drops arguments in both the invocation and the guard (if there is one).
 379      * @param pos the position of the first argument being dropped
 380      * @param valueTypes the types of the values being dropped
 381      * @return an invocation that drops arguments
 382      */
 383     public GuardedInvocation dropArguments(final int pos, final Class<?>... valueTypes) {
 384         return replaceMethods(MethodHandles.dropArguments(invocation, pos, valueTypes), guard == null ? null :
 385             MethodHandles.dropArguments(guard, pos, valueTypes));
 386     }
 387 
 388 
 389     /**
 390      * Composes the invocation, switchpoint, and the guard into a composite method handle that knows how to fall back.
 391      * @param fallback the fallback method handle in case switchpoint is invalidated or guard returns false.
 392      * @return a composite method handle.
 393      */
 394     public MethodHandle compose(final MethodHandle fallback) {
 395         return compose(fallback, fallback, fallback);
 396     }
 397 
 398     /**
 399      * Composes the invocation, switchpoint, and the guard into a composite method handle that knows how to fall back.
 400      * @param switchpointFallback the fallback method handle in case switchpoint is invalidated.
 401      * @param guardFallback the fallback method handle in case guard returns false.
 402      * @param catchFallback the fallback method in case the exception handler triggers
 403      * @return a composite method handle.
 404      */
 405     public MethodHandle compose(final MethodHandle guardFallback, final MethodHandle switchpointFallback, final MethodHandle catchFallback) {
 406         final MethodHandle guarded =
 407                 guard == null ?
 408                         invocation :
 409                         MethodHandles.guardWithTest(
 410                                 guard,
 411                                 invocation,
 412                                 guardFallback);
 413 
 414         final MethodHandle catchGuarded =
 415                 exception == null ?
 416                         guarded :
 417                         MH.catchException(
 418                                 guarded,
 419                                 exception,
 420                                 MethodHandles.dropArguments(
 421                                     catchFallback,
 422                                     0,
 423                                     exception));
 424 
 425         if (switchPoints == null) {
 426             return catchGuarded;
 427         }
 428 
 429         MethodHandle spGuarded = catchGuarded;
 430         for (final SwitchPoint sp : switchPoints) {
 431             spGuarded = sp.guardWithTest(spGuarded, switchpointFallback);
 432         }
 433 
 434         return spGuarded;
 435     }
 436 
 437     private static void assertType(final MethodHandle mh, final MethodType type) {
 438         if(!mh.type().equals(type)) {
 439             throw new WrongMethodTypeException("Expected type: " + type + " actual type: " + mh.type());
 440         }
 441     }
 442 }