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    Redistribution and use in source and binary forms, with or without
37    modification, are permitted provided that the following conditions are
38    met:
39    * Redistributions of source code must retain the above copyright
40      notice, this list of conditions and the following disclaimer.
41    * Redistributions in binary form must reproduce the above copyright
42      notice, this list of conditions and the following disclaimer in the
43      documentation and/or other materials provided with the distribution.
44    * Neither the name of the copyright holder nor the names of
45      contributors may be used to endorse or promote products derived from
46      this software without specific prior written permission.
47 
48    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
49    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
50    TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
51    PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
52    BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
53    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
54    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
55    BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
56    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
57    OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
58    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59 */
60 
61 package jdk.dynalink.linker;
62 
63 import java.lang.invoke.MethodHandle;
64 import java.lang.invoke.MethodHandles;
65 import java.lang.invoke.MethodType;
66 import java.lang.invoke.SwitchPoint;
67 import java.util.List;
68 import java.util.Objects;
69 import java.util.function.Supplier;
70 import jdk.dynalink.CallSiteDescriptor;
71 import jdk.dynalink.linker.support.Guards;
72 
73 /**
74  * Represents a conditionally valid method handle. Usually produced as a return
75  * value of
76  * {@link GuardingDynamicLinker#getGuardedInvocation(LinkRequest, LinkerServices)}
77  * and
78  * {@link GuardingTypeConverterFactory#convertToType(Class, Class, Supplier)}.
79  * It is an immutable tuple of an invocation method handle, a guard method
80  * handle that defines the applicability of the invocation handle, zero or more
81  * switch points that can be used for external invalidation of the invocation
82  * handle, and an exception type that if thrown during an invocation of the
83  * method handle also invalidates it. The invocation handle is suitable for
84  * invocation if the guard handle returns true for its arguments, and as long
85  * as any of the switch points are not invalidated, and as long as it does not
86  * throw an exception of the designated type. The guard, the switch points, and
87  * the exception type are all optional (a guarded invocation having none of them
88  * is unconditionally valid).
89  */
90 public class GuardedInvocation {
91     private final MethodHandle invocation;
92     private final MethodHandle guard;
93     private final Class<? extends Throwable> exception;
94     private final SwitchPoint[] switchPoints;
95 
96     /**
97      * Creates a new unconditional guarded invocation. It is unconditional as it
98      * has no invalidations.
99      *
100      * @param invocation the method handle representing the invocation. Must not
101      * be null.
102      * @throws NullPointerException if invocation is null.
103      */
GuardedInvocation(final MethodHandle invocation)104     public GuardedInvocation(final MethodHandle invocation) {
105         this(invocation, null, (SwitchPoint)null, null);
106     }
107 
108     /**
109      * Creates a new guarded invocation, with a guard method handle.
110      *
111      * @param invocation the method handle representing the invocation. Must not
112      * be null.
113      * @param guard the method handle representing the guard. Must have be
114      * compatible with the {@code invocation} handle as per
115      * {@link MethodHandles#guardWithTest(MethodHandle, MethodHandle, MethodHandle)}.
116      * For some useful guards, check out the {@link Guards} class. It can be
117      * null to represent an unconditional invocation.
118      * @throws NullPointerException if invocation is null.
119      */
GuardedInvocation(final MethodHandle invocation, final MethodHandle guard)120     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard) {
121         this(invocation, guard, (SwitchPoint)null, null);
122     }
123 
124     /**
125      * Creates a new guarded invocation that can be invalidated by a switch
126      * point.
127      *
128      * @param invocation the method handle representing the invocation. Must
129      * not be null.
130      * @param switchPoint the optional switch point that can be used to
131      * invalidate this linkage. It can be null. If it is null, this represents
132      * an unconditional invocation.
133      * @throws NullPointerException if invocation is null.
134      */
GuardedInvocation(final MethodHandle invocation, final SwitchPoint switchPoint)135     public GuardedInvocation(final MethodHandle invocation, final SwitchPoint switchPoint) {
136         this(invocation, null, switchPoint, null);
137     }
138 
139     /**
140      * Creates a new guarded invocation, with both a guard method handle and a
141      * switch point that can be used to invalidate it.
142      *
143      * @param invocation the method handle representing the invocation. Must
144      * not be null.
145      * @param guard the method handle representing the guard. Must have be
146      * compatible with the {@code invocation} handle as per
147      * {@link MethodHandles#guardWithTest(MethodHandle, MethodHandle, MethodHandle)}.
148      * For some useful guards, check out the {@link Guards} class. It can be
149      * null. If both it and the switch point are null, this represents an
150      * unconditional invocation.
151      * @param switchPoint the optional switch point that can be used to
152      * invalidate this linkage.
153      * @throws NullPointerException if invocation is null.
154      */
GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint switchPoint)155     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint switchPoint) {
156         this(invocation, guard, switchPoint, null);
157     }
158 
159     /**
160      * Creates a new guarded invocation, with a guard method handle, a
161      * switch point that can be used to invalidate it, and an exception that if
162      * thrown when invoked also invalidates it.
163      *
164      * @param invocation the method handle representing the invocation. Must not
165      * be null.
166      * @param guard the method handle representing the guard. Must have be
167      * compatible with the {@code invocation} handle as per
168      * {@link MethodHandles#guardWithTest(MethodHandle, MethodHandle, MethodHandle)}.
169      * For some useful guards, check out the {@link Guards} class. It can be
170      * null. If it and the switch point and the exception are all null, this
171      * represents an unconditional invocation.
172      * @param switchPoint the optional switch point that can be used to
173      * invalidate this linkage.
174      * @param exception the optional exception type that is when thrown by the
175      * invocation also invalidates it.
176      * @throws NullPointerException if invocation is null.
177      */
GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint switchPoint, final Class<? extends Throwable> exception)178     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint switchPoint, final Class<? extends Throwable> exception) {
179         this.invocation = Objects.requireNonNull(invocation);
180         this.guard = guard;
181         this.switchPoints = switchPoint == null ? null : new SwitchPoint[] { switchPoint };
182         if (exception != null && !Throwable.class.isAssignableFrom(exception)) {
183             throw new IllegalArgumentException(exception.getName() + " is not assignable from Throwable");
184         }
185         this.exception = exception;
186     }
187 
188     /**
189      * Creates a new guarded invocation, with a guard method handle, any number
190      * of switch points that can be used to invalidate it, and an exception that
191      * if thrown when invoked also invalidates it.
192      *
193      * @param invocation the method handle representing the invocation. Must not
194      * be null.
195      * @param guard the method handle representing the guard. Must have be
196      * compatible with the {@code invocation} handle as per
197      * {@link MethodHandles#guardWithTest(MethodHandle, MethodHandle, MethodHandle)}.
198      * For some useful guards, check out the {@link Guards} class. It can be
199      * null. If it and the exception are both null, and no switch points were
200      * specified, this represents an unconditional invocation.
201      * @param switchPoints optional switch points that can be used to
202      * invalidate this linkage.
203      * @param exception the optional exception type that is when thrown by the
204      * invocation also invalidates it.
205      * @throws NullPointerException if invocation is null.
206      */
GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint[] switchPoints, final Class<? extends Throwable> exception)207     public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint[] switchPoints, final Class<? extends Throwable> exception) {
208         this.invocation = Objects.requireNonNull(invocation);
209         this.guard = guard;
210         this.switchPoints = switchPoints == null ? null : switchPoints.clone();
211         if (exception != null && !Throwable.class.isAssignableFrom(exception)) {
212             throw new IllegalArgumentException(exception.getName() + " is not assignable from Throwable");
213         }
214         this.exception = exception;
215     }
216 
217     /**
218      * Returns the invocation method handle.
219      *
220      * @return the invocation method handle. It will never be null.
221      */
getInvocation()222     public MethodHandle getInvocation() {
223         return invocation;
224     }
225 
226     /**
227      * Returns the guard method handle.
228      *
229      * @return the guard method handle. Can be null.
230      */
getGuard()231     public MethodHandle getGuard() {
232         return guard;
233     }
234 
235     /**
236      * Returns the switch points that can be used to invalidate the linkage of
237      * this invocation handle.
238      *
239      * @return the switch points that can be used to invalidate the linkage of
240      * this invocation handle. Can be null.
241      */
getSwitchPoints()242     public SwitchPoint[] getSwitchPoints() {
243         return switchPoints == null ? null : switchPoints.clone();
244     }
245 
246     /**
247      * Returns the exception type that if thrown by the invocation should
248      * invalidate the linkage of this guarded invocation.
249      *
250      * @return the exception type that if thrown should be used to invalidate
251      * the linkage. Can be null.
252      */
getException()253     public Class<? extends Throwable> getException() {
254         return exception;
255     }
256 
257     /**
258      * Returns true if and only if this guarded invocation has at least one
259      * invalidated switch point.
260      * @return true if and only if this guarded invocation has at least one
261      * invalidated switch point.
262      */
hasBeenInvalidated()263     public boolean hasBeenInvalidated() {
264         if (switchPoints == null) {
265             return false;
266         }
267         for (final SwitchPoint sp : switchPoints) {
268             if (sp.hasBeenInvalidated()) {
269                 return true;
270             }
271         }
272         return false;
273     }
274 
275     /**
276      * Creates a new guarded invocation with different methods, preserving the switch point.
277      *
278      * @param newInvocation the new invocation
279      * @param newGuard the new guard
280      * @return a new guarded invocation with the replaced methods and the same switch point as this invocation.
281      */
replaceMethods(final MethodHandle newInvocation, final MethodHandle newGuard)282     public GuardedInvocation replaceMethods(final MethodHandle newInvocation, final MethodHandle newGuard) {
283         return new GuardedInvocation(newInvocation, newGuard, switchPoints, exception);
284     }
285 
286     /**
287      * Create a new guarded invocation with an added switch point.
288      * @param newSwitchPoint new switch point. Can be null in which case this
289      * method return the current guarded invocation with no changes.
290      * @return a guarded invocation with the added switch point.
291      */
addSwitchPoint(final SwitchPoint newSwitchPoint)292     public GuardedInvocation addSwitchPoint(final SwitchPoint newSwitchPoint) {
293         if (newSwitchPoint == null) {
294             return this;
295         }
296 
297         final SwitchPoint[] newSwitchPoints;
298         if (switchPoints != null) {
299             newSwitchPoints = new SwitchPoint[switchPoints.length + 1];
300             System.arraycopy(switchPoints, 0, newSwitchPoints, 0, switchPoints.length);
301             newSwitchPoints[switchPoints.length] = newSwitchPoint;
302         } else {
303             newSwitchPoints = new SwitchPoint[] { newSwitchPoint };
304         }
305 
306         return new GuardedInvocation(invocation, guard, newSwitchPoints, exception);
307     }
308 
replaceMethodsOrThis(final MethodHandle newInvocation, final MethodHandle newGuard)309     private GuardedInvocation replaceMethodsOrThis(final MethodHandle newInvocation, final MethodHandle newGuard) {
310         if (newInvocation == invocation && newGuard == guard) {
311             return this;
312         }
313         return replaceMethods(newInvocation, newGuard);
314     }
315 
316     /**
317      * Changes the type of the invocation, as if
318      * {@link MethodHandle#asType(MethodType)} was applied to its invocation
319      * and its guard, if it has one (with return type changed to boolean, and
320      * parameter count potentially truncated for the guard). If the invocation
321      * already is of the required type, returns this object.
322      * @param newType the new type of the invocation.
323      * @return a guarded invocation with the new type applied to it.
324      */
asType(final MethodType newType)325     public GuardedInvocation asType(final MethodType newType) {
326         return replaceMethodsOrThis(invocation.asType(newType), guard == null ? null : Guards.asType(guard, newType));
327     }
328 
329     /**
330      * Changes the type of the invocation, as if
331      * {@link LinkerServices#asType(MethodHandle, MethodType)} was applied to
332      * its invocation and its guard, if it has one (with return type changed to
333      * boolean, and parameter count potentially truncated for the guard). If the
334      * invocation already is of the required 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      */
asType(final LinkerServices linkerServices, final MethodType newType)339     public GuardedInvocation asType(final LinkerServices linkerServices, final MethodType newType) {
340         return replaceMethodsOrThis(linkerServices.asType(invocation, newType), guard == null ? null :
341             Guards.asType(linkerServices, guard, newType));
342     }
343 
344     /**
345      * Changes the type of the invocation, as if
346      * {@link LinkerServices#asTypeLosslessReturn(MethodHandle, MethodType)} was
347      * applied to its invocation and
348      * {@link LinkerServices#asType(MethodHandle, MethodType)} applied to its
349      * guard, if it has one (with return type changed to boolean, and parameter
350      * count potentially truncated for the guard). If the invocation doesn't
351      * change its 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      */
asTypeSafeReturn(final LinkerServices linkerServices, final MethodType newType)356     public GuardedInvocation asTypeSafeReturn(final LinkerServices linkerServices, final MethodType newType) {
357         return replaceMethodsOrThis(linkerServices.asTypeLosslessReturn(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 MethodHandle#asType(MethodType)} was applied to its invocation
364      * and its guard, if it has one (with return type changed to boolean for
365      * guard). If the invocation already is of the required type, returns this
366      * object.
367      * @param desc a call descriptor whose method type is adapted.
368      * @return a guarded invocation with the new type applied to it.
369      */
asType(final CallSiteDescriptor desc)370     public GuardedInvocation asType(final CallSiteDescriptor desc) {
371         return asType(desc.getMethodType());
372     }
373 
374     /**
375      * Applies argument filters to both the invocation and the guard
376      * (if it exists and has at least {@code pos + 1} parameters) with
377      * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)}.
378      * @param pos the position of the first argument being filtered
379      * @param filters the argument filters
380      * @return a filtered invocation
381      */
filterArguments(final int pos, final MethodHandle... filters)382     public GuardedInvocation filterArguments(final int pos, final MethodHandle... filters) {
383         return replaceMethods(MethodHandles.filterArguments(invocation, pos, filters),
384                 guard == null || pos >= guard.type().parameterCount() ?
385                         guard : MethodHandles.filterArguments(guard, pos, filters));
386     }
387 
388     /**
389      * Makes an invocation that drops arguments in both the invocation and the
390      * guard (if it exists and has at least {@code pos} parameters) with
391      * {@link MethodHandles#dropArguments(MethodHandle, int, List)}.
392      * @param pos the position of the first argument being dropped
393      * @param valueTypes the types of the values being dropped
394      * @return an invocation that drops arguments
395      */
dropArguments(final int pos, final List<Class<?>> valueTypes)396     public GuardedInvocation dropArguments(final int pos, final List<Class<?>> valueTypes) {
397         return replaceMethods(MethodHandles.dropArguments(invocation, pos, valueTypes),
398                 guard == null || pos > guard.type().parameterCount() ?
399                     guard : MethodHandles.dropArguments(guard, pos, valueTypes));
400     }
401 
402     /**
403      * Makes an invocation that drops arguments in both the invocation and the
404      * guard (if it exists and has at least {@code pos} parameters) with
405      * {@link MethodHandles#dropArguments(MethodHandle, int, Class...)}.
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      */
dropArguments(final int pos, final Class<?>... valueTypes)410     public GuardedInvocation dropArguments(final int pos, final Class<?>... valueTypes) {
411         return replaceMethods(MethodHandles.dropArguments(invocation, pos, valueTypes),
412                 guard == null || pos > guard.type().parameterCount() ?
413                         guard : MethodHandles.dropArguments(guard, pos, valueTypes));
414     }
415 
416 
417     /**
418      * Composes the invocation, guard, switch points, and the exception into a
419      * composite method handle that knows how to fall back when the guard fails
420      * or the invocation is invalidated.
421      * @param fallback the fallback method handle for when a switch point is
422      * invalidated, a guard returns false, or invalidating exception is thrown.
423      * @return a composite method handle.
424      */
compose(final MethodHandle fallback)425     public MethodHandle compose(final MethodHandle fallback) {
426         return compose(fallback, fallback, fallback);
427     }
428 
429     /**
430      * Composes the invocation, guard, switch points, and the exception into a
431      * composite method handle that knows how to fall back when the guard fails
432      * or the invocation is invalidated.
433      * @param switchpointFallback the fallback method handle in case a switch
434      * point is invalidated.
435      * @param guardFallback the fallback method handle in case guard returns
436      * false.
437      * @param catchFallback the fallback method in case the exception handler
438      * triggers.
439      * @return a composite method handle.
440      */
compose(final MethodHandle guardFallback, final MethodHandle switchpointFallback, final MethodHandle catchFallback)441     public MethodHandle compose(final MethodHandle guardFallback, final MethodHandle switchpointFallback, final MethodHandle catchFallback) {
442         final MethodHandle guarded =
443                 guard == null ?
444                         invocation :
445                         MethodHandles.guardWithTest(
446                                 guard,
447                                 invocation,
448                                 guardFallback);
449 
450         final MethodHandle catchGuarded =
451                 exception == null ?
452                         guarded :
453                         MethodHandles.catchException(
454                                 guarded,
455                                 exception,
456                                 MethodHandles.dropArguments(
457                                     catchFallback,
458                                     0,
459                                     exception));
460 
461         if (switchPoints == null) {
462             return catchGuarded;
463         }
464 
465         MethodHandle spGuarded = catchGuarded;
466         for (final SwitchPoint sp : switchPoints) {
467             spGuarded = sp.guardWithTest(spGuarded, switchpointFallback);
468         }
469 
470         return spGuarded;
471     }
472 }
473