Mon, 18 Feb 2013 16:00:15 +0100
8008371: Fix Dynalink compiler warnings and whitespace
Reviewed-by: jlaskey, sundar
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 */
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
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.
40 You may not use this file except in compliance with either the Apache
41 License or the BSD License.
43 If you choose to use this file in compliance with the Apache License, the
44 following notice applies to you:
46 You may obtain a copy of the Apache License at
48 http://www.apache.org/licenses/LICENSE-2.0
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.
56 If you choose to use this file in compliance with the BSD License, the
57 following notice applies to you:
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.
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 */
84 package jdk.internal.dynalink.support;
86 import java.lang.invoke.MethodHandle;
87 import java.lang.invoke.MethodHandles;
88 import java.lang.invoke.MethodType;
89 import java.util.logging.Level;
90 import java.util.logging.Logger;
91 import jdk.internal.dynalink.linker.LinkerServices;
93 /**
94 * Utility methods for creating typical guards. TODO: introduce reasonable caching of created guards.
95 *
96 * @author Attila Szegedi
97 */
98 public class Guards {
99 private static final Logger LOG = Logger
100 .getLogger(Guards.class.getName(), "jdk.internal.dynalink.support.messages");
102 private Guards() {
103 }
105 /**
106 * Creates a guard method handle with arguments of a specified type, but with boolean return value. When invoked, it
107 * returns true if the first argument is of the specified class (exactly of it, not a subclass). The rest of the
108 * arguments will be ignored.
109 *
110 * @param clazz the class of the first argument to test for
111 * @param type the method type
112 * @return a method handle testing whether its first argument is of the specified class.
113 */
114 @SuppressWarnings("boxing")
115 public static MethodHandle isOfClass(Class<?> clazz, MethodType type) {
116 final Class<?> declaredType = type.parameterType(0);
117 if(clazz == declaredType) {
118 LOG.log(Level.WARNING, "isOfClassGuardAlwaysTrue", new Object[] { clazz.getName(), 0, type });
119 return constantTrue(type);
120 }
121 if(!declaredType.isAssignableFrom(clazz)) {
122 LOG.log(Level.WARNING, "isOfClassGuardAlwaysFalse", new Object[] { clazz.getName(), 0, type });
123 return constantFalse(type);
124 }
125 return getClassBoundArgumentTest(IS_OF_CLASS, clazz, 0, type);
126 }
128 /**
129 * Creates a method handle with arguments of a specified type, but with boolean return value. When invoked, it
130 * returns true if the first argument is instance of the specified class or its subclass). The rest of the arguments
131 * will be ignored.
132 *
133 * @param clazz the class of the first argument to test for
134 * @param type the method type
135 * @return a method handle testing whether its first argument is of the specified class or subclass.
136 */
137 public static MethodHandle isInstance(Class<?> clazz, MethodType type) {
138 return isInstance(clazz, 0, type);
139 }
141 /**
142 * Creates a method handle with arguments of a specified type, but with boolean return value. When invoked, it
143 * returns true if the n'th argument is instance of the specified class or its subclass). The rest of the arguments
144 * will be ignored.
145 *
146 * @param clazz the class of the first argument to test for
147 * @param pos the position on the argument list to test
148 * @param type the method type
149 * @return a method handle testing whether its first argument is of the specified class or subclass.
150 */
151 @SuppressWarnings("boxing")
152 public static MethodHandle isInstance(Class<?> clazz, int pos, MethodType type) {
153 final Class<?> declaredType = type.parameterType(pos);
154 if(clazz.isAssignableFrom(declaredType)) {
155 LOG.log(Level.WARNING, "isInstanceGuardAlwaysTrue", new Object[] { clazz.getName(), pos, type });
156 return constantTrue(type);
157 }
158 if(!declaredType.isAssignableFrom(clazz)) {
159 LOG.log(Level.WARNING, "isInstanceGuardAlwaysFalse", new Object[] { clazz.getName(), pos, type });
160 return constantFalse(type);
161 }
162 return getClassBoundArgumentTest(IS_INSTANCE, clazz, pos, type);
163 }
165 /**
166 * Creates a method handle that returns true if the argument in the specified position is a Java array.
167 *
168 * @param pos the position in the argument lit
169 * @param type the method type of the handle
170 * @return a method handle that returns true if the argument in the specified position is a Java array; the rest of
171 * the arguments are ignored.
172 */
173 @SuppressWarnings("boxing")
174 public static MethodHandle isArray(int pos, MethodType type) {
175 final Class<?> declaredType = type.parameterType(pos);
176 if(declaredType.isArray()) {
177 LOG.log(Level.WARNING, "isArrayGuardAlwaysTrue", new Object[] { pos, type });
178 return constantTrue(type);
179 }
180 if(!declaredType.isAssignableFrom(Object[].class)) {
181 LOG.log(Level.WARNING, "isArrayGuardAlwaysFalse", new Object[] { pos, type });
182 return constantFalse(type);
183 }
184 return asType(IS_ARRAY, pos, type);
185 }
187 /**
188 * Return true if it is safe to strongly reference a class from the referred class loader from a class associated
189 * with the referring class loader without risking a class loader memory leak.
190 *
191 * @param referrerLoader the referrer class loader
192 * @param referredLoader the referred class loader
193 * @return true if it is safe to strongly reference the class
194 */
195 public static boolean canReferenceDirectly(ClassLoader referrerLoader, final ClassLoader referredLoader) {
196 if(referredLoader == null) {
197 // Can always refer directly to a system class
198 return true;
199 }
200 if(referrerLoader == null) {
201 // System classes can't refer directly to any non-system class
202 return false;
203 }
204 // Otherwise, can only refer directly to classes residing in same or
205 // parent class loader.
207 ClassLoader referrer = referrerLoader;
208 do {
209 if(referrer == referredLoader) {
210 return true;
211 }
212 referrer = referrer.getParent();
213 } while(referrer != null);
214 return false;
215 }
217 private static MethodHandle getClassBoundArgumentTest(MethodHandle test, Class<?> clazz, int pos, MethodType type) {
218 // Bind the class to the first argument of the test
219 return asType(test.bindTo(clazz), pos, type);
220 }
222 /**
223 * Takes a guard-test method handle, and adapts it to the requested type, returning a boolean. Only applies
224 * conversions as per {@link MethodHandle#asType(MethodType)}.
225 * @param test the test method handle
226 * @param type the type to adapt the method handle to
227 * @return the adapted method handle
228 */
229 public static MethodHandle asType(MethodHandle test, MethodType type) {
230 return test.asType(getTestType(test, type));
231 }
233 /**
234 * Takes a guard-test method handle, and adapts it to the requested type, returning a boolean. Applies the passed
235 * {@link LinkerServices} object's {@link LinkerServices#asType(MethodHandle, MethodType)}.
236 * @param linkerServices the linker services to use for type conversions
237 * @param test the test method handle
238 * @param type the type to adapt the method handle to
239 * @return the adapted method handle
240 */
241 public static MethodHandle asType(LinkerServices linkerServices, MethodHandle test, MethodType type) {
242 return linkerServices.asType(test, getTestType(test, type));
243 }
245 private static MethodType getTestType(MethodHandle test, MethodType type) {
246 return type.dropParameterTypes(test.type().parameterCount(),
247 type.parameterCount()).changeReturnType(boolean.class);
248 }
250 private static MethodHandle asType(MethodHandle test, int pos, MethodType type) {
251 assert test != null;
252 assert type != null;
253 assert type.parameterCount() > 0;
254 assert pos >= 0 && pos < type.parameterCount();
255 assert test.type().parameterCount() == 1;
256 assert test.type().returnType() == Boolean.TYPE;
257 return MethodHandles.permuteArguments(test.asType(test.type().changeParameterType(0, type.parameterType(pos))),
258 type.changeReturnType(Boolean.TYPE), new int[] { pos });
259 }
261 private static final MethodHandle IS_OF_CLASS = new Lookup(MethodHandles.lookup()).findStatic(Guards.class,
262 "isOfClass", MethodType.methodType(Boolean.TYPE, Class.class, Object.class));
264 private static final MethodHandle IS_INSTANCE = Lookup.PUBLIC.findVirtual(Class.class, "isInstance",
265 MethodType.methodType(Boolean.TYPE, Object.class));
267 private static final MethodHandle IS_ARRAY = new Lookup(MethodHandles.lookup()).findStatic(Guards.class, "isArray",
268 MethodType.methodType(Boolean.TYPE, Object.class));
270 private static final MethodHandle IS_IDENTICAL = new Lookup(MethodHandles.lookup()).findStatic(Guards.class,
271 "isIdentical", MethodType.methodType(Boolean.TYPE, Object.class, Object.class));
273 private static final MethodHandle IS_NULL = new Lookup(MethodHandles.lookup()).findStatic(Guards.class,
274 "isNull", MethodType.methodType(Boolean.TYPE, Object.class));
276 private static final MethodHandle IS_NOT_NULL = new Lookup(MethodHandles.lookup()).findStatic(Guards.class,
277 "isNotNull", MethodType.methodType(Boolean.TYPE, Object.class));
279 /**
280 * Creates a guard method that tests its only argument for being of an exact particular class.
281 * @param clazz the class to test for.
282 * @return the desired guard method.
283 */
284 public static MethodHandle getClassGuard(Class<?> clazz) {
285 return IS_OF_CLASS.bindTo(clazz);
286 }
288 /**
289 * Creates a guard method that tests its only argument for being an instance of a particular class.
290 * @param clazz the class to test for.
291 * @return the desired guard method.
292 */
293 public static MethodHandle getInstanceOfGuard(Class<?> clazz) {
294 return IS_INSTANCE.bindTo(clazz);
295 }
297 /**
298 * Creates a guard method that tests its only argument for being referentially identical to another object
299 * @param obj the object used as referential identity test
300 * @return the desired guard method.
301 */
302 public static MethodHandle getIdentityGuard(Object obj) {
303 return IS_IDENTICAL.bindTo(obj);
304 }
306 /**
307 * Returns a guard that tests whether the first argument is null.
308 * @return a guard that tests whether the first argument is null.
309 */
310 public static MethodHandle isNull() {
311 return IS_NULL;
312 }
314 /**
315 * Returns a guard that tests whether the first argument is not null.
316 * @return a guard that tests whether the first argument is not null.
317 */
318 public static MethodHandle isNotNull() {
319 return IS_NOT_NULL;
320 }
322 @SuppressWarnings("unused")
323 private static boolean isNull(Object obj) {
324 return obj == null;
325 }
327 @SuppressWarnings("unused")
328 private static boolean isNotNull(Object obj) {
329 return obj != null;
330 }
332 @SuppressWarnings("unused")
333 private static boolean isArray(Object o) {
334 return o != null && o.getClass().isArray();
335 }
337 @SuppressWarnings("unused")
338 private static boolean isOfClass(Class<?> c, Object o) {
339 return o != null && o.getClass() == c;
340 }
342 @SuppressWarnings("unused")
343 private static boolean isIdentical(Object o1, Object o2) {
344 return o1 == o2;
345 }
347 private static MethodHandle constantTrue(MethodType type) {
348 return constantBoolean(Boolean.TRUE, type);
349 }
351 private static MethodHandle constantFalse(MethodType type) {
352 return constantBoolean(Boolean.FALSE, type);
353 }
355 private static MethodHandle constantBoolean(Boolean value, MethodType type) {
356 return MethodHandles.permuteArguments(MethodHandles.constant(Boolean.TYPE, value),
357 type.changeReturnType(Boolean.TYPE));
358 }
359 }