GuardedInvocation.java revision 1870:c1792836521e
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
84package jdk.dynalink.linker;
85
86import java.lang.invoke.MethodHandle;
87import java.lang.invoke.MethodHandles;
88import java.lang.invoke.MethodType;
89import java.lang.invoke.SwitchPoint;
90import java.util.List;
91import java.util.Objects;
92import java.util.function.Supplier;
93import jdk.dynalink.CallSiteDescriptor;
94import 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 */
113public 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        if (exception != null && !Throwable.class.isAssignableFrom(exception)) {
206            throw new IllegalArgumentException(exception.getName() + " is not assignable from Throwable");
207        }
208        this.exception = exception;
209    }
210
211    /**
212     * Creates a new guarded invocation, with a guard method handle, any number
213     * of switch points that can be used to invalidate it, and an exception that
214     * if thrown when invoked also invalidates it.
215     *
216     * @param invocation the method handle representing the invocation. Must not
217     * be null.
218     * @param guard the method handle representing the guard. Must have be
219     * compatible with the {@code invocation} handle as per
220     * {@link MethodHandles#guardWithTest(MethodHandle, MethodHandle, MethodHandle)}.
221     * For some useful guards, check out the {@link Guards} class. It can be
222     * null. If it and the exception are both null, and no switch points were
223     * specified, this represents an unconditional invocation.
224     * @param switchPoints optional switch points that can be used to
225     * invalidate this linkage.
226     * @param exception the optional exception type that is when thrown by the
227     * invocation also invalidates it.
228     * @throws NullPointerException if invocation is null.
229     */
230    public GuardedInvocation(final MethodHandle invocation, final MethodHandle guard, final SwitchPoint[] switchPoints, final Class<? extends Throwable> exception) {
231        this.invocation = Objects.requireNonNull(invocation);
232        this.guard = guard;
233        this.switchPoints = switchPoints == null ? null : switchPoints.clone();
234        if (exception != null && !Throwable.class.isAssignableFrom(exception)) {
235            throw new IllegalArgumentException(exception.getName() + " is not assignable from Throwable");
236        }
237        this.exception = exception;
238    }
239
240    /**
241     * Returns the invocation method handle.
242     *
243     * @return the invocation method handle. It will never be null.
244     */
245    public MethodHandle getInvocation() {
246        return invocation;
247    }
248
249    /**
250     * Returns the guard method handle.
251     *
252     * @return the guard method handle. Can be null.
253     */
254    public MethodHandle getGuard() {
255        return guard;
256    }
257
258    /**
259     * Returns the switch points that can be used to invalidate the linkage of
260     * this invocation handle.
261     *
262     * @return the switch points that can be used to invalidate the linkage of
263     * this invocation handle. Can be null.
264     */
265    public SwitchPoint[] getSwitchPoints() {
266        return switchPoints == null ? null : switchPoints.clone();
267    }
268
269    /**
270     * Returns the exception type that if thrown by the invocation should
271     * invalidate the linkage of this guarded invocation.
272     *
273     * @return the exception type that if thrown should be used to invalidate
274     * the linkage. Can be null.
275     */
276    public Class<? extends Throwable> getException() {
277        return exception;
278    }
279
280    /**
281     * Returns true if and only if this guarded invocation has at least one
282     * invalidated switch point.
283     * @return true if and only if this guarded invocation has at least one
284     * invalidated switch point.
285     */
286    public boolean hasBeenInvalidated() {
287        if (switchPoints == null) {
288            return false;
289        }
290        for (final SwitchPoint sp : switchPoints) {
291            if (sp.hasBeenInvalidated()) {
292                return true;
293            }
294        }
295        return false;
296    }
297
298    /**
299     * Creates a new guarded invocation with different methods, preserving the switch point.
300     *
301     * @param newInvocation the new invocation
302     * @param newGuard the new guard
303     * @return a new guarded invocation with the replaced methods and the same switch point as this invocation.
304     */
305    public GuardedInvocation replaceMethods(final MethodHandle newInvocation, final MethodHandle newGuard) {
306        return new GuardedInvocation(newInvocation, newGuard, switchPoints, exception);
307    }
308
309    /**
310     * Create a new guarded invocation with an added switch point.
311     * @param newSwitchPoint new switch point. Can be null in which case this
312     * method return the current guarded invocation with no changes.
313     * @return a guarded invocation with the added switch point.
314     */
315    public GuardedInvocation addSwitchPoint(final SwitchPoint newSwitchPoint) {
316        if (newSwitchPoint == null) {
317            return this;
318        }
319
320        final SwitchPoint[] newSwitchPoints;
321        if (switchPoints != null) {
322            newSwitchPoints = new SwitchPoint[switchPoints.length + 1];
323            System.arraycopy(switchPoints, 0, newSwitchPoints, 0, switchPoints.length);
324            newSwitchPoints[switchPoints.length] = newSwitchPoint;
325        } else {
326            newSwitchPoints = new SwitchPoint[] { newSwitchPoint };
327        }
328
329        return new GuardedInvocation(invocation, guard, newSwitchPoints, exception);
330    }
331
332    private GuardedInvocation replaceMethodsOrThis(final MethodHandle newInvocation, final MethodHandle newGuard) {
333        if (newInvocation == invocation && newGuard == guard) {
334            return this;
335        }
336        return replaceMethods(newInvocation, newGuard);
337    }
338
339    /**
340     * Changes the type of the invocation, as if
341     * {@link MethodHandle#asType(MethodType)} was applied to its invocation
342     * and its guard, if it has one (with return type changed to boolean, and
343     * parameter count potentially truncated for the guard). If the invocation
344     * already is of the required type, returns this object.
345     * @param newType the new type of the invocation.
346     * @return a guarded invocation with the new type applied to it.
347     */
348    public GuardedInvocation asType(final MethodType newType) {
349        return replaceMethodsOrThis(invocation.asType(newType), guard == null ? null : Guards.asType(guard, newType));
350    }
351
352    /**
353     * Changes the type of the invocation, as if
354     * {@link LinkerServices#asType(MethodHandle, MethodType)} was applied to
355     * its invocation and its guard, if it has one (with return type changed to
356     * boolean, and parameter count potentially truncated for the guard). If the
357     * invocation already is of the required type, returns this object.
358     * @param linkerServices the linker services to use for the conversion
359     * @param newType the new type of the invocation.
360     * @return a guarded invocation with the new type applied to it.
361     */
362    public GuardedInvocation asType(final LinkerServices linkerServices, final MethodType newType) {
363        return replaceMethodsOrThis(linkerServices.asType(invocation, newType), guard == null ? null :
364            Guards.asType(linkerServices, guard, newType));
365    }
366
367    /**
368     * Changes the type of the invocation, as if
369     * {@link LinkerServices#asTypeLosslessReturn(MethodHandle, MethodType)} was
370     * applied to its invocation and
371     * {@link LinkerServices#asType(MethodHandle, MethodType)} applied to its
372     * guard, if it has one (with return type changed to boolean, and parameter
373     * count potentially truncated for the guard). If the invocation doesn't
374     * change its type, returns this object.
375     * @param linkerServices the linker services to use for the conversion
376     * @param newType the new type of the invocation.
377     * @return a guarded invocation with the new type applied to it.
378     */
379    public GuardedInvocation asTypeSafeReturn(final LinkerServices linkerServices, final MethodType newType) {
380        return replaceMethodsOrThis(linkerServices.asTypeLosslessReturn(invocation, newType), guard == null ? null :
381            Guards.asType(linkerServices, guard, newType));
382    }
383
384    /**
385     * Changes the type of the invocation, as if
386     * {@link MethodHandle#asType(MethodType)} was applied to its invocation
387     * and its guard, if it has one (with return type changed to boolean for
388     * guard). If the invocation already is of the required type, returns this
389     * object.
390     * @param desc a call descriptor whose method type is adapted.
391     * @return a guarded invocation with the new type applied to it.
392     */
393    public GuardedInvocation asType(final CallSiteDescriptor desc) {
394        return asType(desc.getMethodType());
395    }
396
397    /**
398     * Applies argument filters to both the invocation and the guard
399     * (if it exists and has at least {@code pos + 1} parameters) with
400     * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)}.
401     * @param pos the position of the first argument being filtered
402     * @param filters the argument filters
403     * @return a filtered invocation
404     */
405    public GuardedInvocation filterArguments(final int pos, final MethodHandle... filters) {
406        return replaceMethods(MethodHandles.filterArguments(invocation, pos, filters),
407                guard == null || pos >= guard.type().parameterCount() ?
408                        guard : MethodHandles.filterArguments(guard, pos, filters));
409    }
410
411    /**
412     * Makes an invocation that drops arguments in both the invocation and the
413     * guard (if it exists and has at least {@code pos} parameters) with
414     * {@link MethodHandles#dropArguments(MethodHandle, int, List)}.
415     * @param pos the position of the first argument being dropped
416     * @param valueTypes the types of the values being dropped
417     * @return an invocation that drops arguments
418     */
419    public GuardedInvocation dropArguments(final int pos, final List<Class<?>> valueTypes) {
420        return replaceMethods(MethodHandles.dropArguments(invocation, pos, valueTypes),
421                guard == null || pos > guard.type().parameterCount() ?
422                    guard : MethodHandles.dropArguments(guard, pos, valueTypes));
423    }
424
425    /**
426     * Makes an invocation that drops arguments in both the invocation and the
427     * guard (if it exists and has at least {@code pos} parameters) with
428     * {@link MethodHandles#dropArguments(MethodHandle, int, Class...)}.
429     * @param pos the position of the first argument being dropped
430     * @param valueTypes the types of the values being dropped
431     * @return an invocation that drops arguments
432     */
433    public GuardedInvocation dropArguments(final int pos, final Class<?>... valueTypes) {
434        return replaceMethods(MethodHandles.dropArguments(invocation, pos, valueTypes),
435                guard == null || pos > guard.type().parameterCount() ?
436                        guard : MethodHandles.dropArguments(guard, pos, valueTypes));
437    }
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 fallback the fallback method handle for when a switch point is
445     * invalidated, a guard returns false, or invalidating exception is thrown.
446     * @return a composite method handle.
447     */
448    public MethodHandle compose(final MethodHandle fallback) {
449        return compose(fallback, fallback, fallback);
450    }
451
452    /**
453     * Composes the invocation, guard, switch points, and the exception into a
454     * composite method handle that knows how to fall back when the guard fails
455     * or the invocation is invalidated.
456     * @param switchpointFallback the fallback method handle in case a switch
457     * point is invalidated.
458     * @param guardFallback the fallback method handle in case guard returns
459     * false.
460     * @param catchFallback the fallback method in case the exception handler
461     * triggers.
462     * @return a composite method handle.
463     */
464    public MethodHandle compose(final MethodHandle guardFallback, final MethodHandle switchpointFallback, final MethodHandle catchFallback) {
465        final MethodHandle guarded =
466                guard == null ?
467                        invocation :
468                        MethodHandles.guardWithTest(
469                                guard,
470                                invocation,
471                                guardFallback);
472
473        final MethodHandle catchGuarded =
474                exception == null ?
475                        guarded :
476                        MethodHandles.catchException(
477                                guarded,
478                                exception,
479                                MethodHandles.dropArguments(
480                                    catchFallback,
481                                    0,
482                                    exception));
483
484        if (switchPoints == null) {
485            return catchGuarded;
486        }
487
488        MethodHandle spGuarded = catchGuarded;
489        for (final SwitchPoint sp : switchPoints) {
490            spGuarded = sp.guardWithTest(spGuarded, switchpointFallback);
491        }
492
493        return spGuarded;
494    }
495}
496