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