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