Mon, 03 Nov 2014 09:49:52 +0100
8059443: NPE when unboxing return values
Reviewed-by: lagergren, 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.lang.invoke.WrongMethodTypeException;
90 import java.security.AccessController;
91 import java.security.PrivilegedAction;
92 import java.util.LinkedList;
93 import java.util.List;
94 import jdk.internal.dynalink.linker.ConversionComparator;
95 import jdk.internal.dynalink.linker.ConversionComparator.Comparison;
96 import jdk.internal.dynalink.linker.GuardedInvocation;
97 import jdk.internal.dynalink.linker.GuardedTypeConversion;
98 import jdk.internal.dynalink.linker.GuardingTypeConverterFactory;
99 import jdk.internal.dynalink.linker.LinkerServices;
100 import jdk.internal.dynalink.linker.MethodTypeConversionStrategy;
102 /**
103 * A factory for type converters. This class is the main implementation behind the
104 * {@link LinkerServices#asType(MethodHandle, MethodType)}. It manages the known {@link GuardingTypeConverterFactory}
105 * instances and creates appropriate converters for method handles.
106 *
107 * @author Attila Szegedi
108 */
109 public class TypeConverterFactory {
111 private final GuardingTypeConverterFactory[] factories;
112 private final ConversionComparator[] comparators;
113 private final MethodTypeConversionStrategy autoConversionStrategy;
115 private final ClassValue<ClassMap<MethodHandle>> converterMap = new ClassValue<ClassMap<MethodHandle>>() {
116 @Override
117 protected ClassMap<MethodHandle> computeValue(final Class<?> sourceType) {
118 return new ClassMap<MethodHandle>(getClassLoader(sourceType)) {
119 @Override
120 protected MethodHandle computeValue(final Class<?> targetType) {
121 try {
122 return createConverter(sourceType, targetType);
123 } catch (final RuntimeException e) {
124 throw e;
125 } catch (final Exception e) {
126 throw new RuntimeException(e);
127 }
128 }
129 };
130 }
131 };
133 private final ClassValue<ClassMap<MethodHandle>> converterIdentityMap = new ClassValue<ClassMap<MethodHandle>>() {
134 @Override
135 protected ClassMap<MethodHandle> computeValue(final Class<?> sourceType) {
136 return new ClassMap<MethodHandle>(getClassLoader(sourceType)) {
137 @Override
138 protected MethodHandle computeValue(final Class<?> targetType) {
139 if(!canAutoConvert(sourceType, targetType)) {
140 final MethodHandle converter = getCacheableTypeConverter(sourceType, targetType);
141 if(converter != IDENTITY_CONVERSION) {
142 return converter;
143 }
144 }
145 return IDENTITY_CONVERSION.asType(MethodType.methodType(targetType, sourceType));
146 }
147 };
148 }
149 };
151 private final ClassValue<ClassMap<Boolean>> canConvert = new ClassValue<ClassMap<Boolean>>() {
152 @Override
153 protected ClassMap<Boolean> computeValue(final Class<?> sourceType) {
154 return new ClassMap<Boolean>(getClassLoader(sourceType)) {
155 @Override
156 protected Boolean computeValue(final Class<?> targetType) {
157 try {
158 return getTypeConverterNull(sourceType, targetType) != null;
159 } catch (final RuntimeException e) {
160 throw e;
161 } catch (final Exception e) {
162 throw new RuntimeException(e);
163 }
164 }
165 };
166 }
167 };
169 private static final ClassLoader getClassLoader(final Class<?> clazz) {
170 return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
171 @Override
172 public ClassLoader run() {
173 return clazz.getClassLoader();
174 }
175 }, ClassLoaderGetterContextProvider.GET_CLASS_LOADER_CONTEXT);
176 }
178 /**
179 * Creates a new type converter factory from the available {@link GuardingTypeConverterFactory} instances.
180 *
181 * @param factories the {@link GuardingTypeConverterFactory} instances to compose.
182 * @param autoConversionStrategy conversion strategy for automatic type conversions. After
183 * {@link #asType(java.lang.invoke.MethodHandle, java.lang.invoke.MethodType)} has applied all custom
184 * conversions to a method handle, it still needs to effect
185 * {@link TypeUtilities#isMethodInvocationConvertible(Class, Class) method invocation conversions} that
186 * can usually be automatically applied as per
187 * {@link java.lang.invoke.MethodHandle#asType(java.lang.invoke.MethodType)}.
188 * However, sometimes language runtimes will want to customize even those conversions for their own call
189 * sites. A typical example is allowing unboxing of null return values, which is by default prohibited by
190 * ordinary {@code MethodHandles.asType}. In this case, a language runtime can install its own custom
191 * automatic conversion strategy, that can deal with null values. Note that when the strategy's
192 * {@link MethodTypeConversionStrategy#asType(java.lang.invoke.MethodHandle, java.lang.invoke.MethodType)}
193 * is invoked, the custom language conversions will already have been applied to the method handle, so by
194 * design the difference between the handle's current method type and the desired final type will always
195 * only be ones that can be subjected to method invocation conversions. Can be null, in which case no
196 * custom strategy is employed.
197 */
198 public TypeConverterFactory(final Iterable<? extends GuardingTypeConverterFactory> factories,
199 final MethodTypeConversionStrategy autoConversionStrategy) {
200 final List<GuardingTypeConverterFactory> l = new LinkedList<>();
201 final List<ConversionComparator> c = new LinkedList<>();
202 for(final GuardingTypeConverterFactory factory: factories) {
203 l.add(factory);
204 if(factory instanceof ConversionComparator) {
205 c.add((ConversionComparator)factory);
206 }
207 }
208 this.factories = l.toArray(new GuardingTypeConverterFactory[l.size()]);
209 this.comparators = c.toArray(new ConversionComparator[c.size()]);
210 this.autoConversionStrategy = autoConversionStrategy;
211 }
213 /**
214 * Similar to {@link MethodHandle#asType(MethodType)} except it also hooks in method handles produced by
215 * {@link GuardingTypeConverterFactory} implementations, providing for language-specific type coercing of
216 * parameters. For all conversions that are not a JLS method invocation conversion it'll insert
217 * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)} with composite filters
218 * provided by {@link GuardingTypeConverterFactory} implementations. For the remaining JLS method invocation
219 * conversions, it will invoke {@link MethodTypeConversionStrategy#asType(MethodHandle, MethodType)} first
220 * if an automatic conversion strategy was specified in the
221 * {@link #TypeConverterFactory(Iterable, MethodTypeConversionStrategy) constructor}, and finally apply
222 * {@link MethodHandle#asType(MethodType)} for any remaining conversions.
223 *
224 * @param handle target method handle
225 * @param fromType the types of source arguments
226 * @return a method handle that is a suitable combination of {@link MethodHandle#asType(MethodType)},
227 * {@link MethodTypeConversionStrategy#asType(MethodHandle, MethodType)}, and
228 * {@link MethodHandles#filterArguments(MethodHandle, int, MethodHandle...)} with
229 * {@link GuardingTypeConverterFactory} produced type converters as filters.
230 */
231 public MethodHandle asType(final MethodHandle handle, final MethodType fromType) {
232 MethodHandle newHandle = handle;
233 final MethodType toType = newHandle.type();
234 final int l = toType.parameterCount();
235 if(l != fromType.parameterCount()) {
236 throw new WrongMethodTypeException("Parameter counts differ: " + handle.type() + " vs. " + fromType);
237 }
238 int pos = 0;
239 final List<MethodHandle> converters = new LinkedList<>();
240 for(int i = 0; i < l; ++i) {
241 final Class<?> fromParamType = fromType.parameterType(i);
242 final Class<?> toParamType = toType.parameterType(i);
243 if(canAutoConvert(fromParamType, toParamType)) {
244 newHandle = applyConverters(newHandle, pos, converters);
245 } else {
246 final MethodHandle converter = getTypeConverterNull(fromParamType, toParamType);
247 if(converter != null) {
248 if(converters.isEmpty()) {
249 pos = i;
250 }
251 converters.add(converter);
252 } else {
253 newHandle = applyConverters(newHandle, pos, converters);
254 }
255 }
256 }
257 newHandle = applyConverters(newHandle, pos, converters);
259 // Convert return type
260 final Class<?> fromRetType = fromType.returnType();
261 final Class<?> toRetType = toType.returnType();
262 if(fromRetType != Void.TYPE && toRetType != Void.TYPE) {
263 if(!canAutoConvert(toRetType, fromRetType)) {
264 final MethodHandle converter = getTypeConverterNull(toRetType, fromRetType);
265 if(converter != null) {
266 newHandle = MethodHandles.filterReturnValue(newHandle, converter);
267 }
268 }
269 }
271 // Give change to automatic conversion strategy, if one is present.
272 final MethodHandle autoConvertedHandle =
273 autoConversionStrategy != null ? autoConversionStrategy.asType(newHandle, fromType) : newHandle;
275 // Do a final asType for any conversions that remain.
276 return autoConvertedHandle.asType(fromType);
277 }
279 private static MethodHandle applyConverters(final MethodHandle handle, final int pos, final List<MethodHandle> converters) {
280 if(converters.isEmpty()) {
281 return handle;
282 }
283 final MethodHandle newHandle =
284 MethodHandles.filterArguments(handle, pos, converters.toArray(new MethodHandle[converters.size()]));
285 converters.clear();
286 return newHandle;
287 }
289 /**
290 * Returns true if there might exist a conversion between the requested types (either an automatic JVM conversion,
291 * or one provided by any available {@link GuardingTypeConverterFactory}), or false if there definitely does not
292 * exist a conversion between the requested types. Note that returning true does not guarantee that the conversion
293 * will succeed at runtime (notably, if the "from" or "to" types are sufficiently generic), but returning false
294 * guarantees that it would fail.
295 *
296 * @param from the source type for the conversion
297 * @param to the target type for the conversion
298 * @return true if there can be a conversion, false if there can not.
299 */
300 public boolean canConvert(final Class<?> from, final Class<?> to) {
301 return canAutoConvert(from, to) || canConvert.get(from).get(to).booleanValue();
302 }
304 /**
305 * Determines which of the two type conversions from a source type to the two target types is preferred. This is
306 * used for dynamic overloaded method resolution. If the source type is convertible to exactly one target type with
307 * a method invocation conversion, it is chosen, otherwise available {@link ConversionComparator}s are consulted.
308 * @param sourceType the source type.
309 * @param targetType1 one potential target type
310 * @param targetType2 another potential target type.
311 * @return one of Comparison constants that establish which - if any - of the target types is preferable for the
312 * conversion.
313 */
314 public Comparison compareConversion(final Class<?> sourceType, final Class<?> targetType1, final Class<?> targetType2) {
315 for(final ConversionComparator comparator: comparators) {
316 final Comparison result = comparator.compareConversion(sourceType, targetType1, targetType2);
317 if(result != Comparison.INDETERMINATE) {
318 return result;
319 }
320 }
321 if(TypeUtilities.isMethodInvocationConvertible(sourceType, targetType1)) {
322 if(!TypeUtilities.isMethodInvocationConvertible(sourceType, targetType2)) {
323 return Comparison.TYPE_1_BETTER;
324 }
325 } else if(TypeUtilities.isMethodInvocationConvertible(sourceType, targetType2)) {
326 return Comparison.TYPE_2_BETTER;
327 }
328 return Comparison.INDETERMINATE;
329 }
331 /**
332 * Determines whether it's safe to perform an automatic conversion between the source and target class.
333 *
334 * @param fromType convert from this class
335 * @param toType convert to this class
336 * @return true if it's safe to let MethodHandles.convertArguments() to handle this conversion.
337 */
338 /*private*/ static boolean canAutoConvert(final Class<?> fromType, final Class<?> toType) {
339 return TypeUtilities.isMethodInvocationConvertible(fromType, toType);
340 }
342 /*private*/ MethodHandle getCacheableTypeConverterNull(final Class<?> sourceType, final Class<?> targetType) {
343 final MethodHandle converter = getCacheableTypeConverter(sourceType, targetType);
344 return converter == IDENTITY_CONVERSION ? null : converter;
345 }
347 /*private*/ MethodHandle getTypeConverterNull(final Class<?> sourceType, final Class<?> targetType) {
348 try {
349 return getCacheableTypeConverterNull(sourceType, targetType);
350 } catch(final NotCacheableConverter e) {
351 return e.converter;
352 }
353 }
355 /*private*/ MethodHandle getCacheableTypeConverter(final Class<?> sourceType, final Class<?> targetType) {
356 return converterMap.get(sourceType).get(targetType);
357 }
359 /**
360 * Given a source and target type, returns a method handle that converts between them. Never returns null; in worst
361 * case it will return an identity conversion (that might fail for some values at runtime). You can use this method
362 * if you have a piece of your program that is written in Java, and you need to reuse existing type conversion
363 * machinery in a non-invokedynamic context.
364 * @param sourceType the type to convert from
365 * @param targetType the type to convert to
366 * @return a method handle performing the conversion.
367 */
368 public MethodHandle getTypeConverter(final Class<?> sourceType, final Class<?> targetType) {
369 try {
370 return converterIdentityMap.get(sourceType).get(targetType);
371 } catch(final NotCacheableConverter e) {
372 return e.converter;
373 }
374 }
376 /*private*/ MethodHandle createConverter(final Class<?> sourceType, final Class<?> targetType) throws Exception {
377 final MethodType type = MethodType.methodType(targetType, sourceType);
378 final MethodHandle identity = IDENTITY_CONVERSION.asType(type);
379 MethodHandle last = identity;
380 boolean cacheable = true;
381 for(int i = factories.length; i-- > 0;) {
382 final GuardedTypeConversion next = factories[i].convertToType(sourceType, targetType);
383 if(next != null) {
384 cacheable = cacheable && next.isCacheable();
385 final GuardedInvocation conversionInvocation = next.getConversionInvocation();
386 conversionInvocation.assertType(type);
387 last = conversionInvocation.compose(last);
388 }
389 }
390 if(last == identity) {
391 return IDENTITY_CONVERSION;
392 }
393 if(cacheable) {
394 return last;
395 }
396 throw new NotCacheableConverter(last);
397 }
399 /*private*/ static final MethodHandle IDENTITY_CONVERSION = MethodHandles.identity(Object.class);
401 @SuppressWarnings("serial")
402 private static class NotCacheableConverter extends RuntimeException {
403 final MethodHandle converter;
405 NotCacheableConverter(final MethodHandle converter) {
406 super("", null, false, false);
407 this.converter = converter;
408 }
409 }
410 }