attila@90: /* attila@90: * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. attila@90: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. attila@90: * attila@90: * This code is free software; you can redistribute it and/or modify it attila@90: * under the terms of the GNU General Public License version 2 only, as attila@90: * published by the Free Software Foundation. Oracle designates this attila@90: * particular file as subject to the "Classpath" exception as provided attila@90: * by Oracle in the LICENSE file that accompanied this code. attila@90: * attila@90: * This code is distributed in the hope that it will be useful, but WITHOUT attila@90: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or attila@90: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License attila@90: * version 2 for more details (a copy is included in the LICENSE file that attila@90: * accompanied this code). attila@90: * attila@90: * You should have received a copy of the GNU General Public License version attila@90: * 2 along with this work; if not, write to the Free Software Foundation, attila@90: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. attila@90: * attila@90: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA attila@90: * or visit www.oracle.com if you need additional information or have any attila@90: * questions. attila@90: */ attila@90: attila@90: /* attila@90: * This file is available under and governed by the GNU General Public attila@90: * License version 2 only, as published by the Free Software Foundation. attila@90: * However, the following notice accompanied the original version of this attila@90: * file, and Oracle licenses the original version of this file under the BSD attila@90: * license: attila@90: */ attila@90: /* attila@90: Copyright 2009-2013 Attila Szegedi attila@90: attila@90: Licensed under both the Apache License, Version 2.0 (the "Apache License") attila@90: and the BSD License (the "BSD License"), with licensee being free to attila@90: choose either of the two at their discretion. attila@90: attila@90: You may not use this file except in compliance with either the Apache attila@90: License or the BSD License. attila@90: attila@90: If you choose to use this file in compliance with the Apache License, the attila@90: following notice applies to you: attila@90: attila@90: You may obtain a copy of the Apache License at attila@90: attila@90: http://www.apache.org/licenses/LICENSE-2.0 attila@90: attila@90: Unless required by applicable law or agreed to in writing, software attila@90: distributed under the License is distributed on an "AS IS" BASIS, attila@90: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or attila@90: implied. See the License for the specific language governing attila@90: permissions and limitations under the License. attila@90: attila@90: If you choose to use this file in compliance with the BSD License, the attila@90: following notice applies to you: attila@90: attila@90: Redistribution and use in source and binary forms, with or without attila@90: modification, are permitted provided that the following conditions are attila@90: met: attila@90: * Redistributions of source code must retain the above copyright attila@90: notice, this list of conditions and the following disclaimer. attila@90: * Redistributions in binary form must reproduce the above copyright attila@90: notice, this list of conditions and the following disclaimer in the attila@90: documentation and/or other materials provided with the distribution. attila@90: * Neither the name of the copyright holder nor the names of attila@90: contributors may be used to endorse or promote products derived from attila@90: this software without specific prior written permission. attila@90: attila@90: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS attila@90: IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED attila@90: TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A attila@90: PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER attila@90: BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR attila@90: CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF attila@90: SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR attila@90: BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, attila@90: WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR attila@90: OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF attila@90: ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. attila@90: */ attila@90: attila@90: package jdk.internal.dynalink.beans; attila@90: attila@90: import java.lang.invoke.MethodHandle; attila@90: import java.lang.invoke.MethodHandles; attila@90: import java.lang.invoke.MethodType; attila@404: import java.lang.reflect.AccessibleObject; attila@404: import java.lang.reflect.Constructor; attila@90: import java.lang.reflect.Field; attila@404: import java.lang.reflect.Member; attila@90: import java.lang.reflect.Method; attila@90: import java.lang.reflect.Modifier; attila@439: import java.util.Collection; attila@439: import java.util.Collections; attila@90: import java.util.HashMap; attila@90: import java.util.List; attila@90: import java.util.Map; attila@90: import jdk.internal.dynalink.CallSiteDescriptor; attila@90: import jdk.internal.dynalink.beans.GuardedInvocationComponent.ValidationType; attila@90: import jdk.internal.dynalink.linker.GuardedInvocation; attila@90: import jdk.internal.dynalink.linker.GuardingDynamicLinker; attila@90: import jdk.internal.dynalink.linker.LinkRequest; attila@90: import jdk.internal.dynalink.linker.LinkerServices; attila@90: import jdk.internal.dynalink.support.CallSiteDescriptorFactory; attila@90: import jdk.internal.dynalink.support.Guards; attila@90: import jdk.internal.dynalink.support.Lookup; attila@963: import jdk.internal.dynalink.support.TypeUtilities; attila@90: attila@90: /** attila@90: * A base class for both {@link StaticClassLinker} and {@link BeanLinker}. Deals with common aspects of property attila@90: * exposure and method calls for both static and instance facets of a class. attila@90: * attila@90: * @author Attila Szegedi attila@90: */ attila@90: abstract class AbstractJavaLinker implements GuardingDynamicLinker { attila@404: attila@90: final Class clazz; attila@90: private final MethodHandle classGuard; attila@90: private final MethodHandle assignableGuard; attila@404: private final Map propertyGetters = new HashMap<>(); attila@90: private final Map propertySetters = new HashMap<>(); attila@90: private final Map methods = new HashMap<>(); attila@90: attila@962: AbstractJavaLinker(final Class clazz, final MethodHandle classGuard) { attila@90: this(clazz, classGuard, classGuard); attila@90: } attila@90: attila@962: AbstractJavaLinker(final Class clazz, final MethodHandle classGuard, final MethodHandle assignableGuard) { attila@90: this.clazz = clazz; attila@90: this.classGuard = classGuard; attila@90: this.assignableGuard = assignableGuard; attila@90: attila@90: final FacetIntrospector introspector = createFacetIntrospector(); attila@101: // Add methods and properties attila@962: for(final Method method: introspector.getMethods()) { attila@101: final String name = method.getName(); attila@101: // Add method attila@404: addMember(name, method, methods); attila@101: // Add the method as a property getter and/or setter attila@101: if(name.startsWith("get") && name.length() > 3 && method.getParameterTypes().length == 0) { attila@101: // Property getter attila@404: setPropertyGetter(method, 3); attila@101: } else if(name.startsWith("is") && name.length() > 2 && method.getParameterTypes().length == 0 && attila@101: method.getReturnType() == boolean.class) { attila@101: // Boolean property getter attila@404: setPropertyGetter(method, 2); attila@101: } else if(name.startsWith("set") && name.length() > 3 && method.getParameterTypes().length == 1) { attila@101: // Property setter attila@404: addMember(decapitalize(name.substring(3)), method, propertySetters); attila@90: } attila@101: } attila@90: attila@101: // Add field getter/setters as property getters/setters. attila@962: for(final Field field: introspector.getFields()) { attila@101: final String name = field.getName(); attila@101: // Only add a property getter when one is not defined already as a getXxx()/isXxx() method. attila@101: if(!propertyGetters.containsKey(name)) { attila@101: setPropertyGetter(name, introspector.unreflectGetter(field), ValidationType.EXACT_CLASS); attila@90: } attila@101: if(!(Modifier.isFinal(field.getModifiers()) || propertySetters.containsKey(name))) { attila@404: addMember(name, new SimpleDynamicMethod(introspector.unreflectSetter(field), clazz, name), attila@404: propertySetters); attila@101: } attila@101: } attila@90: attila@101: // Add inner classes, but only those for which we don't hide a property with it attila@962: for(final Map.Entry innerClassSpec: introspector.getInnerClassGetters().entrySet()) { attila@101: final String name = innerClassSpec.getKey(); attila@101: if(!propertyGetters.containsKey(name)) { attila@101: setPropertyGetter(name, innerClassSpec.getValue(), ValidationType.EXACT_CLASS); attila@90: } attila@90: } attila@90: } attila@90: attila@962: private static String decapitalize(final String str) { attila@123: assert str != null; attila@123: if(str.isEmpty()) { attila@123: return str; attila@123: } attila@123: attila@123: final char c0 = str.charAt(0); attila@123: if(Character.isLowerCase(c0)) { attila@123: return str; attila@123: } attila@123: attila@123: // If it has two consecutive upper-case characters, i.e. "URL", don't decapitalize attila@123: if(str.length() > 1 && Character.isUpperCase(str.charAt(1))) { attila@123: return str; attila@123: } attila@123: attila@123: final char c[] = str.toCharArray(); attila@123: c[0] = Character.toLowerCase(c0); attila@123: return new String(c); attila@123: } attila@123: attila@90: abstract FacetIntrospector createFacetIntrospector(); attila@90: attila@439: Collection getReadablePropertyNames() { attila@439: return getUnmodifiableKeys(propertyGetters); attila@439: } attila@439: attila@439: Collection getWritablePropertyNames() { attila@439: return getUnmodifiableKeys(propertySetters); attila@439: } attila@439: attila@439: Collection getMethodNames() { attila@439: return getUnmodifiableKeys(methods); attila@439: } attila@439: attila@962: private static Collection getUnmodifiableKeys(final Map m) { attila@439: return Collections.unmodifiableCollection(m.keySet()); attila@439: } attila@439: attila@404: /** attila@404: * Sets the specified dynamic method to be the property getter for the specified property. Note that you can only attila@404: * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties attila@404: * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)} attila@404: * instead. attila@404: * @param name name of the property attila@404: * @param handle the method handle that implements the property getter attila@404: * @param validationType the validation type for the property attila@404: */ attila@962: private void setPropertyGetter(final String name, final SingleDynamicMethod handle, final ValidationType validationType) { attila@404: propertyGetters.put(name, new AnnotatedDynamicMethod(handle, validationType)); attila@90: } attila@90: attila@404: /** attila@404: * Sets the specified reflective method to be the property getter for the specified property. attila@404: * @param getter the getter method attila@404: * @param prefixLen the getter prefix in the method name; should be 3 for getter names starting with "get" and 2 for attila@404: * names starting with "is". attila@404: */ attila@962: private void setPropertyGetter(final Method getter, final int prefixLen) { attila@404: setPropertyGetter(decapitalize(getter.getName().substring(prefixLen)), createDynamicMethod( attila@404: getMostGenericGetter(getter)), ValidationType.INSTANCE_OF); attila@404: } attila@404: attila@404: /** attila@404: * Sets the specified method handle to be the property getter for the specified property. Note that you can only attila@404: * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties attila@404: * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)} attila@404: * instead. attila@404: * @param name name of the property attila@404: * @param handle the method handle that implements the property getter attila@404: * @param validationType the validation type for the property attila@404: */ attila@962: void setPropertyGetter(final String name, final MethodHandle handle, final ValidationType validationType) { attila@404: setPropertyGetter(name, new SimpleDynamicMethod(handle, clazz, name), validationType); attila@404: } attila@404: attila@962: private void addMember(final String name, final AccessibleObject ao, final Map methodMap) { attila@404: addMember(name, createDynamicMethod(ao), methodMap); attila@404: } attila@404: attila@962: private void addMember(final String name, final SingleDynamicMethod method, final Map methodMap) { attila@90: final DynamicMethod existingMethod = methodMap.get(name); attila@404: final DynamicMethod newMethod = mergeMethods(method, existingMethod, clazz, name); attila@90: if(newMethod != existingMethod) { attila@90: methodMap.put(name, newMethod); attila@90: } attila@90: } attila@90: attila@404: /** attila@404: * Given one or more reflective methods or constructors, creates a dynamic method that represents them all. The attila@404: * methods should represent all overloads of the same name (or all constructors of the class). attila@404: * @param members the reflective members attila@404: * @param clazz the class declaring the reflective members attila@404: * @param name the common name of the reflective members. attila@404: * @return a dynamic method representing all the specified reflective members. attila@404: */ attila@962: static DynamicMethod createDynamicMethod(final Iterable members, final Class clazz, final String name) { attila@90: DynamicMethod dynMethod = null; attila@962: for(final AccessibleObject method: members) { attila@404: dynMethod = mergeMethods(createDynamicMethod(method), dynMethod, clazz, name); attila@90: } attila@90: return dynMethod; attila@90: } attila@90: attila@404: /** attila@404: * Given a reflective method or a constructor, creates a dynamic method that represents it. This method will attila@404: * distinguish between caller sensitive and ordinary methods/constructors, and create appropriate caller sensitive attila@404: * dynamic method when needed. attila@404: * @param m the reflective member attila@404: * @return the single dynamic method representing the reflective member attila@404: */ attila@962: private static SingleDynamicMethod createDynamicMethod(final AccessibleObject m) { attila@404: if(CallerSensitiveDetector.isCallerSensitive(m)) { attila@1081: // Method has @CallerSensitive annotation attila@404: return new CallerSensitiveDynamicMethod(m); attila@404: } attila@1081: // Method has no @CallerSensitive annotation attila@1081: final MethodHandle mh; attila@1081: try { attila@1081: mh = unreflectSafely(m); attila@1081: } catch (final IllegalAccessError e) { attila@1081: // java.lang.invoke can in some case conservatively treat as caller sensitive methods that aren't attila@1081: // marked with the annotation. In this case, we'll fall back to treating it as caller sensitive. attila@1081: return new CallerSensitiveDynamicMethod(m); attila@1081: } attila@1081: // Proceed with non-caller sensitive attila@404: final Member member = (Member)m; attila@1081: return new SimpleDynamicMethod(mh, member.getDeclaringClass(), member.getName(), m instanceof Constructor); attila@404: } attila@404: attila@404: /** attila@404: * Unreflects a method handle from a Method or a Constructor using safe (zero-privilege) unreflection. Should be attila@404: * only used for methods and constructors that are not caller sensitive. If a caller sensitive method were attila@404: * unreflected through this mechanism, it would not be a security issue, but would be bound to the zero-privilege attila@404: * unreflector as its caller, and thus completely useless. attila@404: * @param m the method or constructor attila@404: * @return the method handle attila@404: */ attila@962: private static MethodHandle unreflectSafely(final AccessibleObject m) { attila@404: if(m instanceof Method) { attila@404: final Method reflMethod = (Method)m; attila@464: final MethodHandle handle = Lookup.PUBLIC.unreflect(reflMethod); attila@404: if(Modifier.isStatic(reflMethod.getModifiers())) { attila@404: return StaticClassIntrospector.editStaticMethodHandle(handle); attila@404: } attila@404: return handle; attila@404: } attila@464: return StaticClassIntrospector.editConstructorMethodHandle(Lookup.PUBLIC.unreflectConstructor((Constructor)m)); attila@404: } attila@404: attila@962: private static DynamicMethod mergeMethods(final SingleDynamicMethod method, final DynamicMethod existing, final Class clazz, final String name) { attila@90: if(existing == null) { attila@404: return method; attila@404: } else if(existing.contains(method)) { attila@90: return existing; attila@404: } else if(existing instanceof SingleDynamicMethod) { attila@90: final OverloadedDynamicMethod odm = new OverloadedDynamicMethod(clazz, name); attila@404: odm.addMethod(((SingleDynamicMethod)existing)); attila@404: odm.addMethod(method); attila@90: return odm; attila@90: } else if(existing instanceof OverloadedDynamicMethod) { attila@404: ((OverloadedDynamicMethod)existing).addMethod(method); attila@90: return existing; attila@90: } attila@90: throw new AssertionError(); attila@90: } attila@90: attila@90: @Override attila@962: public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) attila@90: throws Exception { attila@90: final LinkRequest ncrequest = request.withoutRuntimeContext(); attila@90: // BeansLinker already checked that the name is at least 2 elements long and the first element is "dyn". attila@90: final CallSiteDescriptor callSiteDescriptor = ncrequest.getCallSiteDescriptor(); attila@90: final String op = callSiteDescriptor.getNameToken(CallSiteDescriptor.OPERATOR); attila@90: // Either dyn:callMethod:name(this[,args]) or dyn:callMethod(this,name[,args]). attila@90: if("callMethod" == op) { attila@90: return getCallPropWithThis(callSiteDescriptor, linkerServices); attila@90: } attila@90: List operations = CallSiteDescriptorFactory.tokenizeOperators(callSiteDescriptor); attila@90: while(!operations.isEmpty()) { attila@90: final GuardedInvocationComponent gic = getGuardedInvocationComponent(callSiteDescriptor, linkerServices, attila@90: operations); attila@90: if(gic != null) { attila@90: return gic.getGuardedInvocation(); attila@90: } attila@90: operations = pop(operations); attila@90: } attila@90: return null; attila@90: } attila@90: attila@962: protected GuardedInvocationComponent getGuardedInvocationComponent(final CallSiteDescriptor callSiteDescriptor, attila@962: final LinkerServices linkerServices, final List operations) throws Exception { attila@90: if(operations.isEmpty()) { attila@90: return null; attila@90: } attila@90: final String op = operations.get(0); attila@90: // Either dyn:getProp:name(this) or dyn:getProp(this, name) attila@90: if("getProp".equals(op)) { attila@90: return getPropertyGetter(callSiteDescriptor, linkerServices, pop(operations)); attila@90: } attila@90: // Either dyn:setProp:name(this, value) or dyn:setProp(this, name, value) attila@90: if("setProp".equals(op)) { attila@90: return getPropertySetter(callSiteDescriptor, linkerServices, pop(operations)); attila@90: } attila@90: // Either dyn:getMethod:name(this), or dyn:getMethod(this, name) attila@90: if("getMethod".equals(op)) { attila@90: return getMethodGetter(callSiteDescriptor, linkerServices, pop(operations)); attila@90: } attila@90: return null; attila@90: } attila@90: attila@962: static final List pop(final List l) { attila@90: return l.subList(1, l.size()); attila@90: } attila@90: attila@962: MethodHandle getClassGuard(final CallSiteDescriptor desc) { attila@90: return getClassGuard(desc.getMethodType()); attila@90: } attila@90: attila@962: MethodHandle getClassGuard(final MethodType type) { attila@90: return Guards.asType(classGuard, type); attila@90: } attila@90: attila@962: GuardedInvocationComponent getClassGuardedInvocationComponent(final MethodHandle invocation, final MethodType type) { attila@90: return new GuardedInvocationComponent(invocation, getClassGuard(type), clazz, ValidationType.EXACT_CLASS); attila@90: } attila@90: attila@963: SingleDynamicMethod getConstructorMethod(final String signature) { attila@963: return null; attila@963: } attila@963: attila@962: private MethodHandle getAssignableGuard(final MethodType type) { attila@90: return Guards.asType(assignableGuard, type); attila@90: } attila@90: attila@962: private GuardedInvocation getCallPropWithThis(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) { attila@90: switch(callSiteDescriptor.getNameTokenCount()) { attila@90: case 3: { attila@404: return createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices, attila@90: callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), methods); attila@90: } attila@90: default: { attila@90: return null; attila@90: } attila@90: } attila@90: } attila@90: attila@962: private GuardedInvocation createGuardedDynamicMethodInvocation(final CallSiteDescriptor callSiteDescriptor, attila@962: final LinkerServices linkerServices, final String methodName, final Map methodMap){ attila@404: final MethodHandle inv = getDynamicMethodInvocation(callSiteDescriptor, linkerServices, methodName, methodMap); attila@404: return inv == null ? null : new GuardedInvocation(inv, getClassGuard(callSiteDescriptor.getMethodType())); attila@90: } attila@90: attila@963: private MethodHandle getDynamicMethodInvocation(final CallSiteDescriptor callSiteDescriptor, attila@962: final LinkerServices linkerServices, final String methodName, final Map methodMap) { attila@90: final DynamicMethod dynaMethod = getDynamicMethod(methodName, methodMap); attila@404: return dynaMethod != null ? dynaMethod.getInvocation(callSiteDescriptor, linkerServices) : null; attila@90: } attila@90: attila@963: private DynamicMethod getDynamicMethod(final String methodName, final Map methodMap) { attila@90: final DynamicMethod dynaMethod = methodMap.get(methodName); attila@90: return dynaMethod != null ? dynaMethod : getExplicitSignatureDynamicMethod(methodName, methodMap); attila@90: } attila@90: attila@963: private SingleDynamicMethod getExplicitSignatureDynamicMethod(final String fullName, attila@962: final Map methodsMap) { attila@90: // What's below is meant to support the "name(type, type, ...)" syntax that programmers can use in a method name attila@90: // to manually pin down an exact overloaded variant. This is not usually required, as the overloaded method attila@90: // resolution works correctly in almost every situation. However, in presence of many language-specific attila@90: // conversions with a radically dynamic language, most overloaded methods will end up being constantly selected attila@404: // at invocation time, so a programmer knowledgeable of the situation might choose to pin down an exact overload attila@90: // for performance reasons. attila@90: attila@90: // Is the method name lexically of the form "name(types)"? attila@963: final int lastChar = fullName.length() - 1; attila@963: if(fullName.charAt(lastChar) != ')') { attila@90: return null; attila@90: } attila@963: final int openBrace = fullName.indexOf('('); attila@90: if(openBrace == -1) { attila@90: return null; attila@90: } attila@90: attila@963: final String name = fullName.substring(0, openBrace); attila@963: final String signature = fullName.substring(openBrace + 1, lastChar); attila@963: attila@90: // Find an existing method for the "name" part attila@963: final DynamicMethod simpleNamedMethod = methodsMap.get(name); attila@90: if(simpleNamedMethod == null) { attila@963: // explicit signature constructor access attila@963: // Java.type("java.awt.Color")["(int,int,int)"] attila@963: // will get Color(int,int,int) constructor of Color class. attila@963: if (name.isEmpty()) { attila@963: return getConstructorMethod(signature); attila@963: } attila@963: attila@90: return null; attila@90: } attila@90: attila@90: // Try to get a narrowed dynamic method for the explicit parameter types. attila@963: return simpleNamedMethod.getMethodForExactParamTypes(signature); attila@90: } attila@90: attila@90: private static final MethodHandle IS_METHOD_HANDLE_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType( attila@90: boolean.class, MethodHandle.class)); attila@90: private static final MethodHandle CONSTANT_NULL_DROP_METHOD_HANDLE = MethodHandles.dropArguments( attila@90: MethodHandles.constant(Object.class, null), 0, MethodHandle.class); attila@90: attila@962: private GuardedInvocationComponent getPropertySetter(final CallSiteDescriptor callSiteDescriptor, attila@962: final LinkerServices linkerServices, final List operations) throws Exception { attila@90: switch(callSiteDescriptor.getNameTokenCount()) { attila@90: case 2: { attila@90: // Must have three arguments: target object, property name, and property value. attila@90: assertParameterCount(callSiteDescriptor, 3); attila@90: attila@963: // We want setters that conform to "Object(O, V)". Note, we aren't doing "R(O, V)" as it might not be attila@963: // valid for us to convert return values proactively. Also, since we don't know what setters will be attila@963: // invoked, we'll conservatively presume Object return type. attila@963: final MethodType type = callSiteDescriptor.getMethodType().changeReturnType(Object.class); attila@963: attila@90: // What's below is basically: attila@90: // foldArguments(guardWithTest(isNotNull, invoke, null|nextComponent.invocation), attila@90: // get_setter_handle(type, linkerServices)) attila@90: // only with a bunch of method signature adjustments. Basically, retrieve method setter attila@90: // MethodHandle; if it is non-null, invoke it, otherwise either return null, or delegate to next attila@90: // component's invocation. attila@90: attila@90: // Call site type is "ret_type(object_type,property_name_type,property_value_type)", which we'll attila@963: // abbreviate to R(O, N, V) going forward, although we don't really use R here (see above about using attila@963: // Object return type). attila@90: final MethodType setterType = type.dropParameterTypes(1, 2); attila@90: // Bind property setter handle to the expected setter type and linker services. Type is attila@90: // MethodHandle(Object, String, Object) attila@404: final MethodHandle boundGetter = MethodHandles.insertArguments(getPropertySetterHandle, 0, attila@404: CallSiteDescriptorFactory.dropParameterTypes(callSiteDescriptor, 1, 2), linkerServices); attila@90: attila@90: // Cast getter to MethodHandle(O, N, V) attila@90: final MethodHandle typedGetter = linkerServices.asType(boundGetter, type.changeReturnType( attila@90: MethodHandle.class)); attila@90: attila@90: // Handle to invoke the setter R(MethodHandle, O, V) attila@90: final MethodHandle invokeHandle = MethodHandles.exactInvoker(setterType); attila@90: // Handle to invoke the setter, dropping unnecessary fold arguments R(MethodHandle, O, N, V) attila@90: final MethodHandle invokeHandleFolded = MethodHandles.dropArguments(invokeHandle, 2, type.parameterType( attila@90: 1)); attila@90: final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor, attila@90: linkerServices, operations); attila@90: attila@90: final MethodHandle fallbackFolded; attila@90: if(nextComponent == null) { attila@963: // Object(MethodHandle)->Object(MethodHandle, O, N, V); returns constant null attila@90: fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_METHOD_HANDLE, 1, attila@90: type.parameterList()).asType(type.insertParameterTypes(0, MethodHandle.class)); attila@90: } else { attila@963: // Object(O, N, V)->Object(MethodHandle, O, N, V); adapts the next component's invocation to drop the attila@90: // extra argument resulting from fold attila@90: fallbackFolded = MethodHandles.dropArguments(nextComponent.getGuardedInvocation().getInvocation(), attila@90: 0, MethodHandle.class); attila@90: } attila@90: attila@90: // fold(R(MethodHandle, O, N, V), MethodHandle(O, N, V)) attila@90: final MethodHandle compositeSetter = MethodHandles.foldArguments(MethodHandles.guardWithTest( attila@90: IS_METHOD_HANDLE_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter); attila@90: if(nextComponent == null) { attila@90: return getClassGuardedInvocationComponent(compositeSetter, type); attila@90: } attila@101: return nextComponent.compose(compositeSetter, getClassGuard(type), clazz, ValidationType.EXACT_CLASS); attila@90: } attila@90: case 3: { attila@90: // Must have two arguments: target object and property value attila@90: assertParameterCount(callSiteDescriptor, 2); attila@404: final GuardedInvocation gi = createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices, attila@404: callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), propertySetters); attila@90: // If we have a property setter with this name, this composite operation will always stop here attila@90: if(gi != null) { attila@90: return new GuardedInvocationComponent(gi, clazz, ValidationType.EXACT_CLASS); attila@90: } attila@90: // If we don't have a property setter with this name, always fall back to the next operation in the attila@90: // composite (if any) attila@90: return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, operations); attila@90: } attila@90: default: { attila@90: // More than two name components; don't know what to do with it. attila@90: return null; attila@90: } attila@90: } attila@90: } attila@90: attila@90: private static final Lookup privateLookup = new Lookup(MethodHandles.lookup()); attila@90: attila@404: private static final MethodHandle IS_ANNOTATED_METHOD_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType( attila@404: boolean.class, AnnotatedDynamicMethod.class)); attila@404: private static final MethodHandle CONSTANT_NULL_DROP_ANNOTATED_METHOD = MethodHandles.dropArguments( attila@404: MethodHandles.constant(Object.class, null), 0, AnnotatedDynamicMethod.class); attila@404: private static final MethodHandle GET_ANNOTATED_METHOD = privateLookup.findVirtual(AnnotatedDynamicMethod.class, attila@404: "getTarget", MethodType.methodType(MethodHandle.class, MethodHandles.Lookup.class)); attila@404: private static final MethodHandle GETTER_INVOKER = MethodHandles.invoker(MethodType.methodType(Object.class, Object.class)); attila@90: attila@962: private GuardedInvocationComponent getPropertyGetter(final CallSiteDescriptor callSiteDescriptor, attila@962: final LinkerServices linkerServices, final List ops) throws Exception { attila@90: switch(callSiteDescriptor.getNameTokenCount()) { attila@90: case 2: { attila@963: // Since we can't know what kind of a getter we'll get back on different invocations, we'll just attila@963: // conservatively presume Object. Note we can't just coerce to a narrower call site type as the linking attila@963: // runtime might not allow coercing at that call site. attila@963: final MethodType type = callSiteDescriptor.getMethodType().changeReturnType(Object.class); attila@90: // Must have exactly two arguments: receiver and name attila@90: assertParameterCount(callSiteDescriptor, 2); attila@90: attila@90: // What's below is basically: attila@90: // foldArguments(guardWithTest(isNotNull, invoke(get_handle), null|nextComponent.invocation), get_getter_handle) attila@90: // only with a bunch of method signature adjustments. Basically, retrieve method getter attila@404: // AnnotatedDynamicMethod; if it is non-null, invoke its "handle" field, otherwise either return null, attila@90: // or delegate to next component's invocation. attila@90: attila@90: final MethodHandle typedGetter = linkerServices.asType(getPropertyGetterHandle, type.changeReturnType( attila@404: AnnotatedDynamicMethod.class)); attila@404: final MethodHandle callSiteBoundMethodGetter = MethodHandles.insertArguments( attila@404: GET_ANNOTATED_METHOD, 1, callSiteDescriptor.getLookup()); attila@404: final MethodHandle callSiteBoundInvoker = MethodHandles.filterArguments(GETTER_INVOKER, 0, attila@404: callSiteBoundMethodGetter); attila@963: // Object(AnnotatedDynamicMethod, Object)->Object(AnnotatedDynamicMethod, T0) attila@404: final MethodHandle invokeHandleTyped = linkerServices.asType(callSiteBoundInvoker, attila@404: MethodType.methodType(type.returnType(), AnnotatedDynamicMethod.class, type.parameterType(0))); attila@90: // Since it's in the target of a fold, drop the unnecessary second argument attila@963: // Object(AnnotatedDynamicMethod, T0)->Object(AnnotatedDynamicMethod, T0, T1) attila@90: final MethodHandle invokeHandleFolded = MethodHandles.dropArguments(invokeHandleTyped, 2, attila@90: type.parameterType(1)); attila@90: final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor, attila@90: linkerServices, ops); attila@90: attila@90: final MethodHandle fallbackFolded; attila@90: if(nextComponent == null) { attila@963: // Object(AnnotatedDynamicMethod)->Object(AnnotatedDynamicMethod, T0, T1); returns constant null attila@404: fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_ANNOTATED_METHOD, 1, attila@404: type.parameterList()).asType(type.insertParameterTypes(0, AnnotatedDynamicMethod.class)); attila@90: } else { attila@963: // Object(T0, T1)->Object(AnnotatedDynamicMethod, T0, T1); adapts the next component's invocation to attila@963: // drop the extra argument resulting from fold and to change its return type to Object. attila@963: final MethodHandle nextInvocation = nextComponent.getGuardedInvocation().getInvocation(); attila@963: final MethodType nextType = nextInvocation.type(); attila@963: fallbackFolded = MethodHandles.dropArguments(nextInvocation.asType( attila@963: nextType.changeReturnType(Object.class)), 0, AnnotatedDynamicMethod.class); attila@90: } attila@90: attila@963: // fold(Object(AnnotatedDynamicMethod, T0, T1), AnnotatedDynamicMethod(T0, T1)) attila@90: final MethodHandle compositeGetter = MethodHandles.foldArguments(MethodHandles.guardWithTest( attila@404: IS_ANNOTATED_METHOD_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter); attila@90: if(nextComponent == null) { attila@90: return getClassGuardedInvocationComponent(compositeGetter, type); attila@90: } attila@101: return nextComponent.compose(compositeGetter, getClassGuard(type), clazz, ValidationType.EXACT_CLASS); attila@90: } attila@90: case 3: { attila@90: // Must have exactly one argument: receiver attila@90: assertParameterCount(callSiteDescriptor, 1); attila@90: // Fixed name attila@404: final AnnotatedDynamicMethod annGetter = propertyGetters.get(callSiteDescriptor.getNameToken( attila@90: CallSiteDescriptor.NAME_OPERAND)); attila@90: if(annGetter == null) { attila@90: // We have no such property, always delegate to the next component operation attila@90: return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, ops); attila@90: } attila@404: final MethodHandle getter = annGetter.getInvocation(callSiteDescriptor, linkerServices); attila@90: // NOTE: since property getters (not field getters!) are no-arg, we don't have to worry about them being attila@90: // overloaded in a subclass. Therefore, we can discover the most abstract superclass that has the attila@90: // method, and use that as the guard with Guards.isInstance() for a more stably linked call site. If attila@90: // we're linking against a field getter, don't make the assumption. attila@90: // NOTE: No delegation to the next component operation if we have a property with this name, even if its attila@90: // value is null. attila@90: final ValidationType validationType = annGetter.validationType; attila@404: // TODO: we aren't using the type that declares the most generic getter here! attila@963: return new GuardedInvocationComponent(getter, getGuard(validationType, attila@963: callSiteDescriptor.getMethodType()), clazz, validationType); attila@90: } attila@90: default: { attila@90: // Can't do anything with more than 3 name components attila@90: return null; attila@90: } attila@90: } attila@90: } attila@90: attila@962: private MethodHandle getGuard(final ValidationType validationType, final MethodType methodType) { attila@90: switch(validationType) { attila@90: case EXACT_CLASS: { attila@90: return getClassGuard(methodType); attila@90: } attila@90: case INSTANCE_OF: { attila@90: return getAssignableGuard(methodType); attila@90: } attila@90: case IS_ARRAY: { attila@90: return Guards.isArray(0, methodType); attila@90: } attila@90: case NONE: { attila@90: return null; attila@90: } attila@101: default: { attila@101: throw new AssertionError(); attila@101: } attila@90: } attila@90: } attila@90: attila@963: private static final MethodHandle IS_DYNAMIC_METHOD = Guards.isInstance(DynamicMethod.class, attila@963: MethodType.methodType(boolean.class, Object.class)); attila@963: private static final MethodHandle OBJECT_IDENTITY = MethodHandles.identity(Object.class); attila@90: attila@962: private GuardedInvocationComponent getMethodGetter(final CallSiteDescriptor callSiteDescriptor, attila@962: final LinkerServices linkerServices, final List ops) throws Exception { attila@963: // The created method handle will always return a DynamicMethod (or null), but since we don't want that type to attila@963: // be visible outside of this linker, declare it to return Object. attila@963: final MethodType type = callSiteDescriptor.getMethodType().changeReturnType(Object.class); attila@90: switch(callSiteDescriptor.getNameTokenCount()) { attila@90: case 2: { attila@90: // Must have exactly two arguments: receiver and name attila@90: assertParameterCount(callSiteDescriptor, 2); attila@90: final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor, attila@90: linkerServices, ops); attila@963: if(nextComponent == null || !TypeUtilities.areAssignable(DynamicMethod.class, attila@963: nextComponent.getGuardedInvocation().getInvocation().type().returnType())) { attila@963: // No next component operation, or it can never produce a dynamic method; just return a component attila@963: // for this operation. attila@90: return getClassGuardedInvocationComponent(linkerServices.asType(getDynamicMethod, type), type); attila@101: } attila@90: attila@101: // What's below is basically: attila@101: // foldArguments(guardWithTest(isNotNull, identity, nextComponent.invocation), getter) only with a attila@101: // bunch of method signature adjustments. Basically, execute method getter; if it returns a non-null attila@101: // DynamicMethod, use identity to return it, otherwise delegate to nextComponent's invocation. attila@90: attila@963: final MethodHandle typedGetter = linkerServices.asType(getDynamicMethod, type); attila@101: // Since it is part of the foldArgument() target, it will have extra args that we need to drop. attila@101: final MethodHandle returnMethodHandle = linkerServices.asType(MethodHandles.dropArguments( attila@963: OBJECT_IDENTITY, 1, type.parameterList()), type.insertParameterTypes(0, Object.class)); attila@101: final MethodHandle nextComponentInvocation = nextComponent.getGuardedInvocation().getInvocation(); attila@963: // The assumption is that getGuardedInvocationComponent() already asType()'d it correctly modulo the attila@963: // return type. attila@963: assert nextComponentInvocation.type().changeReturnType(type.returnType()).equals(type); attila@101: // Since it is part of the foldArgument() target, we have to drop an extra arg it receives. attila@101: final MethodHandle nextCombinedInvocation = MethodHandles.dropArguments(nextComponentInvocation, 0, attila@963: Object.class); attila@101: // Assemble it all into a fold(guard(isNotNull, identity, nextInvocation), get) attila@101: final MethodHandle compositeGetter = MethodHandles.foldArguments(MethodHandles.guardWithTest( attila@963: IS_DYNAMIC_METHOD, returnMethodHandle, nextCombinedInvocation), typedGetter); attila@101: attila@101: return nextComponent.compose(compositeGetter, getClassGuard(type), clazz, ValidationType.EXACT_CLASS); attila@90: } attila@90: case 3: { attila@90: // Must have exactly one argument: receiver attila@90: assertParameterCount(callSiteDescriptor, 1); attila@90: final DynamicMethod method = getDynamicMethod(callSiteDescriptor.getNameToken( attila@90: CallSiteDescriptor.NAME_OPERAND)); attila@90: if(method == null) { attila@90: // We have no such method, always delegate to the next component attila@90: return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, ops); attila@90: } attila@90: // No delegation to the next component of the composite operation; if we have a method with that name, attila@90: // we'll always return it at this point. attila@90: return getClassGuardedInvocationComponent(linkerServices.asType(MethodHandles.dropArguments( attila@963: MethodHandles.constant(Object.class, method), 0, type.parameterType(0)), type), type); attila@90: } attila@90: default: { attila@90: // Can't do anything with more than 3 name components attila@90: return null; attila@90: } attila@90: } attila@90: } attila@90: attila@963: static class MethodPair { attila@963: final MethodHandle method1; attila@963: final MethodHandle method2; attila@963: attila@963: MethodPair(final MethodHandle method1, final MethodHandle method2) { attila@963: this.method1 = method1; attila@963: this.method2 = method2; attila@963: } attila@963: attila@963: MethodHandle guardWithTest(final MethodHandle test) { attila@963: return MethodHandles.guardWithTest(test, method1, method2); attila@963: } attila@963: } attila@963: attila@963: static MethodPair matchReturnTypes(final MethodHandle m1, final MethodHandle m2) { attila@963: final MethodType type1 = m1.type(); attila@963: final MethodType type2 = m2.type(); attila@963: final Class commonRetType = TypeUtilities.getCommonLosslessConversionType(type1.returnType(), attila@963: type2.returnType()); attila@963: return new MethodPair( attila@963: m1.asType(type1.changeReturnType(commonRetType)), attila@963: m2.asType(type2.changeReturnType(commonRetType))); attila@963: } attila@963: attila@962: private static void assertParameterCount(final CallSiteDescriptor descriptor, final int paramCount) { attila@90: if(descriptor.getMethodType().parameterCount() != paramCount) { attila@90: throw new BootstrapMethodError(descriptor.getName() + " must have exactly " + paramCount + " parameters."); attila@90: } attila@90: } attila@90: attila@90: private static MethodHandle GET_PROPERTY_GETTER_HANDLE = MethodHandles.dropArguments(privateLookup.findOwnSpecial( attila@90: "getPropertyGetterHandle", Object.class, Object.class), 1, Object.class); attila@90: private final MethodHandle getPropertyGetterHandle = GET_PROPERTY_GETTER_HANDLE.bindTo(this); attila@90: attila@90: /** attila@90: * @param id the property ID attila@90: * @return the method handle for retrieving the property, or null if the property does not exist attila@90: */ attila@90: @SuppressWarnings("unused") attila@962: private Object getPropertyGetterHandle(final Object id) { attila@90: return propertyGetters.get(id); attila@90: } attila@90: attila@90: // Type is MethodHandle(BeanLinker, MethodType, LinkerServices, Object, String, Object), of which the two "Object" attila@90: // args are dropped; this makes handles with first three args conform to "Object, String, Object" though, which is attila@90: // a typical property setter with variable name signature (target, name, value). attila@90: private static final MethodHandle GET_PROPERTY_SETTER_HANDLE = MethodHandles.dropArguments(MethodHandles.dropArguments( attila@404: privateLookup.findOwnSpecial("getPropertySetterHandle", MethodHandle.class, CallSiteDescriptor.class, attila@90: LinkerServices.class, Object.class), 3, Object.class), 5, Object.class); attila@90: // Type is MethodHandle(MethodType, LinkerServices, Object, String, Object) attila@90: private final MethodHandle getPropertySetterHandle = GET_PROPERTY_SETTER_HANDLE.bindTo(this); attila@90: attila@90: @SuppressWarnings("unused") attila@962: private MethodHandle getPropertySetterHandle(final CallSiteDescriptor setterDescriptor, final LinkerServices linkerServices, attila@962: final Object id) { attila@404: return getDynamicMethodInvocation(setterDescriptor, linkerServices, String.valueOf(id), propertySetters); attila@90: } attila@90: attila@90: private static MethodHandle GET_DYNAMIC_METHOD = MethodHandles.dropArguments(privateLookup.findOwnSpecial( attila@963: "getDynamicMethod", Object.class, Object.class), 1, Object.class); attila@90: private final MethodHandle getDynamicMethod = GET_DYNAMIC_METHOD.bindTo(this); attila@90: attila@90: @SuppressWarnings("unused") attila@963: // This method is marked to return Object instead of DynamicMethod as it's used as a linking component and we don't attila@963: // want to make the DynamicMethod type observable externally (e.g. as the return type of a MethodHandle returned for attila@963: // "dyn:getMethod" linking). attila@963: private Object getDynamicMethod(final Object name) { attila@90: return getDynamicMethod(String.valueOf(name), methods); attila@90: } attila@90: attila@90: /** attila@90: * Returns a dynamic method of the specified name. attila@90: * attila@90: * @param name name of the method attila@90: * @return the dynamic method (either {@link SimpleDynamicMethod} or {@link OverloadedDynamicMethod}, or null if the attila@90: * method with the specified name does not exist. attila@90: */ attila@962: DynamicMethod getDynamicMethod(final String name) { attila@90: return getDynamicMethod(name, methods); attila@90: } attila@90: attila@90: /** attila@90: * Find the most generic superclass that declares this getter. Since getters have zero args (aside from the attila@90: * receiver), they can't be overloaded, so we're free to link with an instanceof guard for the most generic one, attila@90: * creating more stable call sites. attila@90: * @param getter the getter attila@90: * @return getter with same name, declared on the most generic superclass/interface of the declaring class attila@90: */ attila@962: private static Method getMostGenericGetter(final Method getter) { attila@90: return getMostGenericGetter(getter.getName(), getter.getReturnType(), getter.getDeclaringClass()); attila@90: } attila@90: attila@962: private static Method getMostGenericGetter(final String name, final Class returnType, final Class declaringClass) { attila@90: if(declaringClass == null) { attila@90: return null; attila@90: } attila@90: // Prefer interfaces attila@962: for(final Class itf: declaringClass.getInterfaces()) { attila@90: final Method itfGetter = getMostGenericGetter(name, returnType, itf); attila@90: if(itfGetter != null) { attila@90: return itfGetter; attila@90: } attila@90: } attila@90: final Method superGetter = getMostGenericGetter(name, returnType, declaringClass.getSuperclass()); attila@90: if(superGetter != null) { attila@90: return superGetter; attila@90: } attila@90: if(!CheckRestrictedPackage.isRestrictedClass(declaringClass)) { attila@90: try { attila@90: return declaringClass.getMethod(name); attila@962: } catch(final NoSuchMethodException e) { attila@90: // Intentionally ignored, meant to fall through attila@90: } attila@90: } attila@90: return null; attila@90: } attila@90: attila@404: private static final class AnnotatedDynamicMethod { attila@404: private final SingleDynamicMethod method; attila@90: /*private*/ final ValidationType validationType; attila@90: attila@962: AnnotatedDynamicMethod(final SingleDynamicMethod method, final ValidationType validationType) { attila@404: this.method = method; attila@90: this.validationType = validationType; attila@90: } attila@404: attila@962: MethodHandle getInvocation(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) { attila@404: return method.getInvocation(callSiteDescriptor, linkerServices); attila@404: } attila@404: attila@404: @SuppressWarnings("unused") attila@962: MethodHandle getTarget(final MethodHandles.Lookup lookup) { attila@962: final MethodHandle inv = method.getTarget(lookup); attila@404: assert inv != null; attila@404: return inv; attila@404: } attila@90: } attila@101: }