src/jdk/internal/dynalink/beans/AbstractJavaLinker.java

Thu, 24 May 2018 16:39:31 +0800

author
aoqi
date
Thu, 24 May 2018 16:39:31 +0800
changeset 1959
61ffdd1b89f2
parent 1651
86ed55da74ab
parent 1490
d85f981c8cf8
permissions
-rw-r--r--

Merge

aoqi@0 1 /*
aoqi@0 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
aoqi@0 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
aoqi@0 4 *
aoqi@0 5 * This code is free software; you can redistribute it and/or modify it
aoqi@0 6 * under the terms of the GNU General Public License version 2 only, as
aoqi@0 7 * published by the Free Software Foundation. Oracle designates this
aoqi@0 8 * particular file as subject to the "Classpath" exception as provided
aoqi@0 9 * by Oracle in the LICENSE file that accompanied this code.
aoqi@0 10 *
aoqi@0 11 * This code is distributed in the hope that it will be useful, but WITHOUT
aoqi@0 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
aoqi@0 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
aoqi@0 14 * version 2 for more details (a copy is included in the LICENSE file that
aoqi@0 15 * accompanied this code).
aoqi@0 16 *
aoqi@0 17 * You should have received a copy of the GNU General Public License version
aoqi@0 18 * 2 along with this work; if not, write to the Free Software Foundation,
aoqi@0 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
aoqi@0 20 *
aoqi@0 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
aoqi@0 22 * or visit www.oracle.com if you need additional information or have any
aoqi@0 23 * questions.
aoqi@0 24 */
aoqi@0 25
aoqi@0 26 /*
aoqi@0 27 * This file is available under and governed by the GNU General Public
aoqi@0 28 * License version 2 only, as published by the Free Software Foundation.
aoqi@0 29 * However, the following notice accompanied the original version of this
aoqi@0 30 * file, and Oracle licenses the original version of this file under the BSD
aoqi@0 31 * license:
aoqi@0 32 */
aoqi@0 33 /*
aoqi@0 34 Copyright 2009-2013 Attila Szegedi
aoqi@0 35
aoqi@0 36 Licensed under both the Apache License, Version 2.0 (the "Apache License")
aoqi@0 37 and the BSD License (the "BSD License"), with licensee being free to
aoqi@0 38 choose either of the two at their discretion.
aoqi@0 39
aoqi@0 40 You may not use this file except in compliance with either the Apache
aoqi@0 41 License or the BSD License.
aoqi@0 42
aoqi@0 43 If you choose to use this file in compliance with the Apache License, the
aoqi@0 44 following notice applies to you:
aoqi@0 45
aoqi@0 46 You may obtain a copy of the Apache License at
aoqi@0 47
aoqi@0 48 http://www.apache.org/licenses/LICENSE-2.0
aoqi@0 49
aoqi@0 50 Unless required by applicable law or agreed to in writing, software
aoqi@0 51 distributed under the License is distributed on an "AS IS" BASIS,
aoqi@0 52 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
aoqi@0 53 implied. See the License for the specific language governing
aoqi@0 54 permissions and limitations under the License.
aoqi@0 55
aoqi@0 56 If you choose to use this file in compliance with the BSD License, the
aoqi@0 57 following notice applies to you:
aoqi@0 58
aoqi@0 59 Redistribution and use in source and binary forms, with or without
aoqi@0 60 modification, are permitted provided that the following conditions are
aoqi@0 61 met:
aoqi@0 62 * Redistributions of source code must retain the above copyright
aoqi@0 63 notice, this list of conditions and the following disclaimer.
aoqi@0 64 * Redistributions in binary form must reproduce the above copyright
aoqi@0 65 notice, this list of conditions and the following disclaimer in the
aoqi@0 66 documentation and/or other materials provided with the distribution.
aoqi@0 67 * Neither the name of the copyright holder nor the names of
aoqi@0 68 contributors may be used to endorse or promote products derived from
aoqi@0 69 this software without specific prior written permission.
aoqi@0 70
aoqi@0 71 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
aoqi@0 72 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
aoqi@0 73 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
aoqi@0 74 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
aoqi@0 75 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
aoqi@0 76 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
aoqi@0 77 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
aoqi@0 78 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
aoqi@0 79 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
aoqi@0 80 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
aoqi@0 81 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
aoqi@0 82 */
aoqi@0 83
aoqi@0 84 package jdk.internal.dynalink.beans;
aoqi@0 85
aoqi@0 86 import java.lang.invoke.MethodHandle;
aoqi@0 87 import java.lang.invoke.MethodHandles;
aoqi@0 88 import java.lang.invoke.MethodType;
aoqi@0 89 import java.lang.reflect.AccessibleObject;
aoqi@0 90 import java.lang.reflect.Constructor;
aoqi@0 91 import java.lang.reflect.Field;
aoqi@0 92 import java.lang.reflect.Member;
aoqi@0 93 import java.lang.reflect.Method;
aoqi@0 94 import java.lang.reflect.Modifier;
aoqi@0 95 import java.util.Collection;
aoqi@0 96 import java.util.Collections;
aoqi@0 97 import java.util.HashMap;
aoqi@0 98 import java.util.List;
aoqi@0 99 import java.util.Map;
aoqi@0 100 import jdk.internal.dynalink.CallSiteDescriptor;
aoqi@0 101 import jdk.internal.dynalink.beans.GuardedInvocationComponent.ValidationType;
aoqi@0 102 import jdk.internal.dynalink.linker.GuardedInvocation;
aoqi@0 103 import jdk.internal.dynalink.linker.GuardingDynamicLinker;
aoqi@0 104 import jdk.internal.dynalink.linker.LinkRequest;
aoqi@0 105 import jdk.internal.dynalink.linker.LinkerServices;
aoqi@0 106 import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
aoqi@0 107 import jdk.internal.dynalink.support.Guards;
aoqi@0 108 import jdk.internal.dynalink.support.Lookup;
attila@963 109 import jdk.internal.dynalink.support.TypeUtilities;
aoqi@0 110
aoqi@0 111 /**
aoqi@0 112 * A base class for both {@link StaticClassLinker} and {@link BeanLinker}. Deals with common aspects of property
aoqi@0 113 * exposure and method calls for both static and instance facets of a class.
aoqi@0 114 *
aoqi@0 115 * @author Attila Szegedi
aoqi@0 116 */
aoqi@0 117 abstract class AbstractJavaLinker implements GuardingDynamicLinker {
aoqi@0 118
aoqi@0 119 final Class<?> clazz;
aoqi@0 120 private final MethodHandle classGuard;
aoqi@0 121 private final MethodHandle assignableGuard;
aoqi@0 122 private final Map<String, AnnotatedDynamicMethod> propertyGetters = new HashMap<>();
aoqi@0 123 private final Map<String, DynamicMethod> propertySetters = new HashMap<>();
aoqi@0 124 private final Map<String, DynamicMethod> methods = new HashMap<>();
aoqi@0 125
attila@962 126 AbstractJavaLinker(final Class<?> clazz, final MethodHandle classGuard) {
aoqi@0 127 this(clazz, classGuard, classGuard);
aoqi@0 128 }
aoqi@0 129
attila@962 130 AbstractJavaLinker(final Class<?> clazz, final MethodHandle classGuard, final MethodHandle assignableGuard) {
aoqi@0 131 this.clazz = clazz;
aoqi@0 132 this.classGuard = classGuard;
aoqi@0 133 this.assignableGuard = assignableGuard;
aoqi@0 134
aoqi@0 135 final FacetIntrospector introspector = createFacetIntrospector();
aoqi@0 136 // Add methods and properties
attila@962 137 for(final Method method: introspector.getMethods()) {
aoqi@0 138 final String name = method.getName();
aoqi@0 139 // Add method
aoqi@0 140 addMember(name, method, methods);
aoqi@0 141 // Add the method as a property getter and/or setter
aoqi@0 142 if(name.startsWith("get") && name.length() > 3 && method.getParameterTypes().length == 0) {
aoqi@0 143 // Property getter
aoqi@0 144 setPropertyGetter(method, 3);
aoqi@0 145 } else if(name.startsWith("is") && name.length() > 2 && method.getParameterTypes().length == 0 &&
aoqi@0 146 method.getReturnType() == boolean.class) {
aoqi@0 147 // Boolean property getter
aoqi@0 148 setPropertyGetter(method, 2);
aoqi@0 149 } else if(name.startsWith("set") && name.length() > 3 && method.getParameterTypes().length == 1) {
aoqi@0 150 // Property setter
aoqi@0 151 addMember(decapitalize(name.substring(3)), method, propertySetters);
aoqi@0 152 }
aoqi@0 153 }
aoqi@0 154
aoqi@0 155 // Add field getter/setters as property getters/setters.
attila@962 156 for(final Field field: introspector.getFields()) {
aoqi@0 157 final String name = field.getName();
aoqi@0 158 // Only add a property getter when one is not defined already as a getXxx()/isXxx() method.
aoqi@0 159 if(!propertyGetters.containsKey(name)) {
aoqi@0 160 setPropertyGetter(name, introspector.unreflectGetter(field), ValidationType.EXACT_CLASS);
aoqi@0 161 }
aoqi@0 162 if(!(Modifier.isFinal(field.getModifiers()) || propertySetters.containsKey(name))) {
aoqi@0 163 addMember(name, new SimpleDynamicMethod(introspector.unreflectSetter(field), clazz, name),
aoqi@0 164 propertySetters);
aoqi@0 165 }
aoqi@0 166 }
aoqi@0 167
aoqi@0 168 // Add inner classes, but only those for which we don't hide a property with it
attila@962 169 for(final Map.Entry<String, MethodHandle> innerClassSpec: introspector.getInnerClassGetters().entrySet()) {
aoqi@0 170 final String name = innerClassSpec.getKey();
aoqi@0 171 if(!propertyGetters.containsKey(name)) {
aoqi@0 172 setPropertyGetter(name, innerClassSpec.getValue(), ValidationType.EXACT_CLASS);
aoqi@0 173 }
aoqi@0 174 }
aoqi@0 175 }
aoqi@0 176
attila@962 177 private static String decapitalize(final String str) {
aoqi@0 178 assert str != null;
aoqi@0 179 if(str.isEmpty()) {
aoqi@0 180 return str;
aoqi@0 181 }
aoqi@0 182
aoqi@0 183 final char c0 = str.charAt(0);
aoqi@0 184 if(Character.isLowerCase(c0)) {
aoqi@0 185 return str;
aoqi@0 186 }
aoqi@0 187
aoqi@0 188 // If it has two consecutive upper-case characters, i.e. "URL", don't decapitalize
aoqi@0 189 if(str.length() > 1 && Character.isUpperCase(str.charAt(1))) {
aoqi@0 190 return str;
aoqi@0 191 }
aoqi@0 192
aoqi@0 193 final char c[] = str.toCharArray();
aoqi@0 194 c[0] = Character.toLowerCase(c0);
aoqi@0 195 return new String(c);
aoqi@0 196 }
aoqi@0 197
aoqi@0 198 abstract FacetIntrospector createFacetIntrospector();
aoqi@0 199
aoqi@0 200 Collection<String> getReadablePropertyNames() {
aoqi@0 201 return getUnmodifiableKeys(propertyGetters);
aoqi@0 202 }
aoqi@0 203
aoqi@0 204 Collection<String> getWritablePropertyNames() {
aoqi@0 205 return getUnmodifiableKeys(propertySetters);
aoqi@0 206 }
aoqi@0 207
aoqi@0 208 Collection<String> getMethodNames() {
aoqi@0 209 return getUnmodifiableKeys(methods);
aoqi@0 210 }
aoqi@0 211
attila@962 212 private static Collection<String> getUnmodifiableKeys(final Map<String, ?> m) {
aoqi@0 213 return Collections.unmodifiableCollection(m.keySet());
aoqi@0 214 }
aoqi@0 215
aoqi@0 216 /**
aoqi@0 217 * Sets the specified dynamic method to be the property getter for the specified property. Note that you can only
aoqi@0 218 * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties
aoqi@0 219 * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)}
aoqi@0 220 * instead.
aoqi@0 221 * @param name name of the property
aoqi@0 222 * @param handle the method handle that implements the property getter
aoqi@0 223 * @param validationType the validation type for the property
aoqi@0 224 */
attila@962 225 private void setPropertyGetter(final String name, final SingleDynamicMethod handle, final ValidationType validationType) {
aoqi@0 226 propertyGetters.put(name, new AnnotatedDynamicMethod(handle, validationType));
aoqi@0 227 }
aoqi@0 228
aoqi@0 229 /**
aoqi@0 230 * Sets the specified reflective method to be the property getter for the specified property.
aoqi@0 231 * @param getter the getter method
aoqi@0 232 * @param prefixLen the getter prefix in the method name; should be 3 for getter names starting with "get" and 2 for
aoqi@0 233 * names starting with "is".
aoqi@0 234 */
attila@962 235 private void setPropertyGetter(final Method getter, final int prefixLen) {
aoqi@0 236 setPropertyGetter(decapitalize(getter.getName().substring(prefixLen)), createDynamicMethod(
aoqi@0 237 getMostGenericGetter(getter)), ValidationType.INSTANCE_OF);
aoqi@0 238 }
aoqi@0 239
aoqi@0 240 /**
aoqi@0 241 * Sets the specified method handle to be the property getter for the specified property. Note that you can only
aoqi@0 242 * use this when you're certain that the method handle does not belong to a caller-sensitive method. For properties
aoqi@0 243 * that are caller-sensitive, you must use {@link #setPropertyGetter(String, SingleDynamicMethod, ValidationType)}
aoqi@0 244 * instead.
aoqi@0 245 * @param name name of the property
aoqi@0 246 * @param handle the method handle that implements the property getter
aoqi@0 247 * @param validationType the validation type for the property
aoqi@0 248 */
attila@962 249 void setPropertyGetter(final String name, final MethodHandle handle, final ValidationType validationType) {
aoqi@0 250 setPropertyGetter(name, new SimpleDynamicMethod(handle, clazz, name), validationType);
aoqi@0 251 }
aoqi@0 252
attila@962 253 private void addMember(final String name, final AccessibleObject ao, final Map<String, DynamicMethod> methodMap) {
aoqi@0 254 addMember(name, createDynamicMethod(ao), methodMap);
aoqi@0 255 }
aoqi@0 256
attila@962 257 private void addMember(final String name, final SingleDynamicMethod method, final Map<String, DynamicMethod> methodMap) {
aoqi@0 258 final DynamicMethod existingMethod = methodMap.get(name);
aoqi@0 259 final DynamicMethod newMethod = mergeMethods(method, existingMethod, clazz, name);
aoqi@0 260 if(newMethod != existingMethod) {
aoqi@0 261 methodMap.put(name, newMethod);
aoqi@0 262 }
aoqi@0 263 }
aoqi@0 264
aoqi@0 265 /**
aoqi@0 266 * Given one or more reflective methods or constructors, creates a dynamic method that represents them all. The
aoqi@0 267 * methods should represent all overloads of the same name (or all constructors of the class).
aoqi@0 268 * @param members the reflective members
aoqi@0 269 * @param clazz the class declaring the reflective members
aoqi@0 270 * @param name the common name of the reflective members.
aoqi@0 271 * @return a dynamic method representing all the specified reflective members.
aoqi@0 272 */
attila@962 273 static DynamicMethod createDynamicMethod(final Iterable<? extends AccessibleObject> members, final Class<?> clazz, final String name) {
aoqi@0 274 DynamicMethod dynMethod = null;
attila@962 275 for(final AccessibleObject method: members) {
aoqi@0 276 dynMethod = mergeMethods(createDynamicMethod(method), dynMethod, clazz, name);
aoqi@0 277 }
aoqi@0 278 return dynMethod;
aoqi@0 279 }
aoqi@0 280
aoqi@0 281 /**
aoqi@0 282 * Given a reflective method or a constructor, creates a dynamic method that represents it. This method will
aoqi@0 283 * distinguish between caller sensitive and ordinary methods/constructors, and create appropriate caller sensitive
aoqi@0 284 * dynamic method when needed.
aoqi@0 285 * @param m the reflective member
aoqi@0 286 * @return the single dynamic method representing the reflective member
aoqi@0 287 */
attila@962 288 private static SingleDynamicMethod createDynamicMethod(final AccessibleObject m) {
aoqi@0 289 if(CallerSensitiveDetector.isCallerSensitive(m)) {
attila@1081 290 // Method has @CallerSensitive annotation
aoqi@0 291 return new CallerSensitiveDynamicMethod(m);
aoqi@0 292 }
attila@1081 293 // Method has no @CallerSensitive annotation
attila@1081 294 final MethodHandle mh;
attila@1081 295 try {
attila@1081 296 mh = unreflectSafely(m);
attila@1081 297 } catch (final IllegalAccessError e) {
attila@1081 298 // java.lang.invoke can in some case conservatively treat as caller sensitive methods that aren't
attila@1081 299 // marked with the annotation. In this case, we'll fall back to treating it as caller sensitive.
attila@1081 300 return new CallerSensitiveDynamicMethod(m);
attila@1081 301 }
attila@1081 302 // Proceed with non-caller sensitive
aoqi@0 303 final Member member = (Member)m;
attila@1081 304 return new SimpleDynamicMethod(mh, member.getDeclaringClass(), member.getName(), m instanceof Constructor);
aoqi@0 305 }
aoqi@0 306
aoqi@0 307 /**
aoqi@0 308 * Unreflects a method handle from a Method or a Constructor using safe (zero-privilege) unreflection. Should be
aoqi@0 309 * only used for methods and constructors that are not caller sensitive. If a caller sensitive method were
aoqi@0 310 * unreflected through this mechanism, it would not be a security issue, but would be bound to the zero-privilege
aoqi@0 311 * unreflector as its caller, and thus completely useless.
aoqi@0 312 * @param m the method or constructor
aoqi@0 313 * @return the method handle
aoqi@0 314 */
attila@962 315 private static MethodHandle unreflectSafely(final AccessibleObject m) {
aoqi@0 316 if(m instanceof Method) {
aoqi@0 317 final Method reflMethod = (Method)m;
aoqi@0 318 final MethodHandle handle = Lookup.PUBLIC.unreflect(reflMethod);
aoqi@0 319 if(Modifier.isStatic(reflMethod.getModifiers())) {
aoqi@0 320 return StaticClassIntrospector.editStaticMethodHandle(handle);
aoqi@0 321 }
aoqi@0 322 return handle;
aoqi@0 323 }
aoqi@0 324 return StaticClassIntrospector.editConstructorMethodHandle(Lookup.PUBLIC.unreflectConstructor((Constructor<?>)m));
aoqi@0 325 }
aoqi@0 326
attila@962 327 private static DynamicMethod mergeMethods(final SingleDynamicMethod method, final DynamicMethod existing, final Class<?> clazz, final String name) {
aoqi@0 328 if(existing == null) {
aoqi@0 329 return method;
aoqi@0 330 } else if(existing.contains(method)) {
aoqi@0 331 return existing;
aoqi@0 332 } else if(existing instanceof SingleDynamicMethod) {
aoqi@0 333 final OverloadedDynamicMethod odm = new OverloadedDynamicMethod(clazz, name);
aoqi@0 334 odm.addMethod(((SingleDynamicMethod)existing));
aoqi@0 335 odm.addMethod(method);
aoqi@0 336 return odm;
aoqi@0 337 } else if(existing instanceof OverloadedDynamicMethod) {
aoqi@0 338 ((OverloadedDynamicMethod)existing).addMethod(method);
aoqi@0 339 return existing;
aoqi@0 340 }
aoqi@0 341 throw new AssertionError();
aoqi@0 342 }
aoqi@0 343
aoqi@0 344 @Override
attila@962 345 public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices)
aoqi@0 346 throws Exception {
aoqi@0 347 final LinkRequest ncrequest = request.withoutRuntimeContext();
aoqi@0 348 // BeansLinker already checked that the name is at least 2 elements long and the first element is "dyn".
aoqi@0 349 final CallSiteDescriptor callSiteDescriptor = ncrequest.getCallSiteDescriptor();
aoqi@0 350 final String op = callSiteDescriptor.getNameToken(CallSiteDescriptor.OPERATOR);
aoqi@0 351 // Either dyn:callMethod:name(this[,args]) or dyn:callMethod(this,name[,args]).
aoqi@0 352 if("callMethod" == op) {
aoqi@0 353 return getCallPropWithThis(callSiteDescriptor, linkerServices);
aoqi@0 354 }
aoqi@0 355 List<String> operations = CallSiteDescriptorFactory.tokenizeOperators(callSiteDescriptor);
aoqi@0 356 while(!operations.isEmpty()) {
aoqi@0 357 final GuardedInvocationComponent gic = getGuardedInvocationComponent(callSiteDescriptor, linkerServices,
aoqi@0 358 operations);
aoqi@0 359 if(gic != null) {
aoqi@0 360 return gic.getGuardedInvocation();
aoqi@0 361 }
aoqi@0 362 operations = pop(operations);
aoqi@0 363 }
aoqi@0 364 return null;
aoqi@0 365 }
aoqi@0 366
attila@962 367 protected GuardedInvocationComponent getGuardedInvocationComponent(final CallSiteDescriptor callSiteDescriptor,
attila@962 368 final LinkerServices linkerServices, final List<String> operations) throws Exception {
aoqi@0 369 if(operations.isEmpty()) {
aoqi@0 370 return null;
aoqi@0 371 }
aoqi@0 372 final String op = operations.get(0);
aoqi@0 373 // Either dyn:getProp:name(this) or dyn:getProp(this, name)
aoqi@0 374 if("getProp".equals(op)) {
aoqi@0 375 return getPropertyGetter(callSiteDescriptor, linkerServices, pop(operations));
aoqi@0 376 }
aoqi@0 377 // Either dyn:setProp:name(this, value) or dyn:setProp(this, name, value)
aoqi@0 378 if("setProp".equals(op)) {
aoqi@0 379 return getPropertySetter(callSiteDescriptor, linkerServices, pop(operations));
aoqi@0 380 }
aoqi@0 381 // Either dyn:getMethod:name(this), or dyn:getMethod(this, name)
aoqi@0 382 if("getMethod".equals(op)) {
aoqi@0 383 return getMethodGetter(callSiteDescriptor, linkerServices, pop(operations));
aoqi@0 384 }
aoqi@0 385 return null;
aoqi@0 386 }
aoqi@0 387
attila@962 388 static final <T> List<T> pop(final List<T> l) {
aoqi@0 389 return l.subList(1, l.size());
aoqi@0 390 }
aoqi@0 391
attila@962 392 MethodHandle getClassGuard(final CallSiteDescriptor desc) {
aoqi@0 393 return getClassGuard(desc.getMethodType());
aoqi@0 394 }
aoqi@0 395
attila@962 396 MethodHandle getClassGuard(final MethodType type) {
aoqi@0 397 return Guards.asType(classGuard, type);
aoqi@0 398 }
aoqi@0 399
attila@962 400 GuardedInvocationComponent getClassGuardedInvocationComponent(final MethodHandle invocation, final MethodType type) {
aoqi@0 401 return new GuardedInvocationComponent(invocation, getClassGuard(type), clazz, ValidationType.EXACT_CLASS);
aoqi@0 402 }
aoqi@0 403
attila@963 404 SingleDynamicMethod getConstructorMethod(final String signature) {
attila@963 405 return null;
attila@963 406 }
attila@963 407
attila@962 408 private MethodHandle getAssignableGuard(final MethodType type) {
aoqi@0 409 return Guards.asType(assignableGuard, type);
aoqi@0 410 }
aoqi@0 411
attila@962 412 private GuardedInvocation getCallPropWithThis(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) {
aoqi@0 413 switch(callSiteDescriptor.getNameTokenCount()) {
aoqi@0 414 case 3: {
aoqi@0 415 return createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices,
aoqi@0 416 callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), methods);
aoqi@0 417 }
aoqi@0 418 default: {
aoqi@0 419 return null;
aoqi@0 420 }
aoqi@0 421 }
aoqi@0 422 }
aoqi@0 423
attila@962 424 private GuardedInvocation createGuardedDynamicMethodInvocation(final CallSiteDescriptor callSiteDescriptor,
attila@962 425 final LinkerServices linkerServices, final String methodName, final Map<String, DynamicMethod> methodMap){
aoqi@0 426 final MethodHandle inv = getDynamicMethodInvocation(callSiteDescriptor, linkerServices, methodName, methodMap);
aoqi@0 427 return inv == null ? null : new GuardedInvocation(inv, getClassGuard(callSiteDescriptor.getMethodType()));
aoqi@0 428 }
aoqi@0 429
attila@963 430 private MethodHandle getDynamicMethodInvocation(final CallSiteDescriptor callSiteDescriptor,
attila@962 431 final LinkerServices linkerServices, final String methodName, final Map<String, DynamicMethod> methodMap) {
aoqi@0 432 final DynamicMethod dynaMethod = getDynamicMethod(methodName, methodMap);
aoqi@0 433 return dynaMethod != null ? dynaMethod.getInvocation(callSiteDescriptor, linkerServices) : null;
aoqi@0 434 }
aoqi@0 435
attila@963 436 private DynamicMethod getDynamicMethod(final String methodName, final Map<String, DynamicMethod> methodMap) {
aoqi@0 437 final DynamicMethod dynaMethod = methodMap.get(methodName);
aoqi@0 438 return dynaMethod != null ? dynaMethod : getExplicitSignatureDynamicMethod(methodName, methodMap);
aoqi@0 439 }
aoqi@0 440
attila@963 441 private SingleDynamicMethod getExplicitSignatureDynamicMethod(final String fullName,
attila@962 442 final Map<String, DynamicMethod> methodsMap) {
aoqi@0 443 // What's below is meant to support the "name(type, type, ...)" syntax that programmers can use in a method name
aoqi@0 444 // to manually pin down an exact overloaded variant. This is not usually required, as the overloaded method
aoqi@0 445 // resolution works correctly in almost every situation. However, in presence of many language-specific
aoqi@0 446 // conversions with a radically dynamic language, most overloaded methods will end up being constantly selected
aoqi@0 447 // at invocation time, so a programmer knowledgeable of the situation might choose to pin down an exact overload
aoqi@0 448 // for performance reasons.
aoqi@0 449
aoqi@0 450 // Is the method name lexically of the form "name(types)"?
attila@963 451 final int lastChar = fullName.length() - 1;
attila@963 452 if(fullName.charAt(lastChar) != ')') {
aoqi@0 453 return null;
aoqi@0 454 }
attila@963 455 final int openBrace = fullName.indexOf('(');
aoqi@0 456 if(openBrace == -1) {
aoqi@0 457 return null;
aoqi@0 458 }
aoqi@0 459
attila@963 460 final String name = fullName.substring(0, openBrace);
attila@963 461 final String signature = fullName.substring(openBrace + 1, lastChar);
attila@963 462
aoqi@0 463 // Find an existing method for the "name" part
attila@963 464 final DynamicMethod simpleNamedMethod = methodsMap.get(name);
aoqi@0 465 if(simpleNamedMethod == null) {
attila@963 466 // explicit signature constructor access
attila@963 467 // Java.type("java.awt.Color")["(int,int,int)"]
attila@963 468 // will get Color(int,int,int) constructor of Color class.
attila@963 469 if (name.isEmpty()) {
attila@963 470 return getConstructorMethod(signature);
attila@963 471 }
attila@963 472
aoqi@0 473 return null;
aoqi@0 474 }
aoqi@0 475
aoqi@0 476 // Try to get a narrowed dynamic method for the explicit parameter types.
attila@963 477 return simpleNamedMethod.getMethodForExactParamTypes(signature);
aoqi@0 478 }
aoqi@0 479
aoqi@0 480 private static final MethodHandle IS_METHOD_HANDLE_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType(
aoqi@0 481 boolean.class, MethodHandle.class));
aoqi@0 482 private static final MethodHandle CONSTANT_NULL_DROP_METHOD_HANDLE = MethodHandles.dropArguments(
aoqi@0 483 MethodHandles.constant(Object.class, null), 0, MethodHandle.class);
aoqi@0 484
attila@962 485 private GuardedInvocationComponent getPropertySetter(final CallSiteDescriptor callSiteDescriptor,
attila@962 486 final LinkerServices linkerServices, final List<String> operations) throws Exception {
aoqi@0 487 switch(callSiteDescriptor.getNameTokenCount()) {
aoqi@0 488 case 2: {
aoqi@0 489 // Must have three arguments: target object, property name, and property value.
aoqi@0 490 assertParameterCount(callSiteDescriptor, 3);
aoqi@0 491
attila@963 492 // We want setters that conform to "Object(O, V)". Note, we aren't doing "R(O, V)" as it might not be
attila@963 493 // valid for us to convert return values proactively. Also, since we don't know what setters will be
attila@1183 494 // invoked, we'll conservatively presume Object return type. The one exception is void return.
attila@1183 495 final MethodType origType = callSiteDescriptor.getMethodType();
attila@1183 496 final MethodType type = origType.returnType() == void.class ? origType : origType.changeReturnType(Object.class);
attila@963 497
aoqi@0 498 // What's below is basically:
aoqi@0 499 // foldArguments(guardWithTest(isNotNull, invoke, null|nextComponent.invocation),
aoqi@0 500 // get_setter_handle(type, linkerServices))
aoqi@0 501 // only with a bunch of method signature adjustments. Basically, retrieve method setter
aoqi@0 502 // MethodHandle; if it is non-null, invoke it, otherwise either return null, or delegate to next
aoqi@0 503 // component's invocation.
aoqi@0 504
aoqi@0 505 // Call site type is "ret_type(object_type,property_name_type,property_value_type)", which we'll
attila@963 506 // abbreviate to R(O, N, V) going forward, although we don't really use R here (see above about using
attila@963 507 // Object return type).
aoqi@0 508 final MethodType setterType = type.dropParameterTypes(1, 2);
aoqi@0 509 // Bind property setter handle to the expected setter type and linker services. Type is
aoqi@0 510 // MethodHandle(Object, String, Object)
aoqi@0 511 final MethodHandle boundGetter = MethodHandles.insertArguments(getPropertySetterHandle, 0,
attila@1183 512 callSiteDescriptor.changeMethodType(setterType), linkerServices);
aoqi@0 513
aoqi@0 514 // Cast getter to MethodHandle(O, N, V)
aoqi@0 515 final MethodHandle typedGetter = linkerServices.asType(boundGetter, type.changeReturnType(
aoqi@0 516 MethodHandle.class));
aoqi@0 517
aoqi@0 518 // Handle to invoke the setter R(MethodHandle, O, V)
aoqi@0 519 final MethodHandle invokeHandle = MethodHandles.exactInvoker(setterType);
aoqi@0 520 // Handle to invoke the setter, dropping unnecessary fold arguments R(MethodHandle, O, N, V)
aoqi@0 521 final MethodHandle invokeHandleFolded = MethodHandles.dropArguments(invokeHandle, 2, type.parameterType(
aoqi@0 522 1));
aoqi@0 523 final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor,
aoqi@0 524 linkerServices, operations);
aoqi@0 525
aoqi@0 526 final MethodHandle fallbackFolded;
aoqi@0 527 if(nextComponent == null) {
attila@963 528 // Object(MethodHandle)->Object(MethodHandle, O, N, V); returns constant null
aoqi@0 529 fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_METHOD_HANDLE, 1,
aoqi@0 530 type.parameterList()).asType(type.insertParameterTypes(0, MethodHandle.class));
aoqi@0 531 } else {
attila@963 532 // Object(O, N, V)->Object(MethodHandle, O, N, V); adapts the next component's invocation to drop the
aoqi@0 533 // extra argument resulting from fold
aoqi@0 534 fallbackFolded = MethodHandles.dropArguments(nextComponent.getGuardedInvocation().getInvocation(),
aoqi@0 535 0, MethodHandle.class);
aoqi@0 536 }
aoqi@0 537
aoqi@0 538 // fold(R(MethodHandle, O, N, V), MethodHandle(O, N, V))
aoqi@0 539 final MethodHandle compositeSetter = MethodHandles.foldArguments(MethodHandles.guardWithTest(
aoqi@0 540 IS_METHOD_HANDLE_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter);
aoqi@0 541 if(nextComponent == null) {
aoqi@0 542 return getClassGuardedInvocationComponent(compositeSetter, type);
aoqi@0 543 }
aoqi@0 544 return nextComponent.compose(compositeSetter, getClassGuard(type), clazz, ValidationType.EXACT_CLASS);
aoqi@0 545 }
aoqi@0 546 case 3: {
aoqi@0 547 // Must have two arguments: target object and property value
aoqi@0 548 assertParameterCount(callSiteDescriptor, 2);
aoqi@0 549 final GuardedInvocation gi = createGuardedDynamicMethodInvocation(callSiteDescriptor, linkerServices,
aoqi@0 550 callSiteDescriptor.getNameToken(CallSiteDescriptor.NAME_OPERAND), propertySetters);
aoqi@0 551 // If we have a property setter with this name, this composite operation will always stop here
aoqi@0 552 if(gi != null) {
aoqi@0 553 return new GuardedInvocationComponent(gi, clazz, ValidationType.EXACT_CLASS);
aoqi@0 554 }
aoqi@0 555 // If we don't have a property setter with this name, always fall back to the next operation in the
aoqi@0 556 // composite (if any)
aoqi@0 557 return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, operations);
aoqi@0 558 }
aoqi@0 559 default: {
aoqi@0 560 // More than two name components; don't know what to do with it.
aoqi@0 561 return null;
aoqi@0 562 }
aoqi@0 563 }
aoqi@0 564 }
aoqi@0 565
aoqi@0 566 private static final Lookup privateLookup = new Lookup(MethodHandles.lookup());
aoqi@0 567
aoqi@0 568 private static final MethodHandle IS_ANNOTATED_METHOD_NOT_NULL = Guards.isNotNull().asType(MethodType.methodType(
aoqi@0 569 boolean.class, AnnotatedDynamicMethod.class));
aoqi@0 570 private static final MethodHandle CONSTANT_NULL_DROP_ANNOTATED_METHOD = MethodHandles.dropArguments(
aoqi@0 571 MethodHandles.constant(Object.class, null), 0, AnnotatedDynamicMethod.class);
aoqi@0 572 private static final MethodHandle GET_ANNOTATED_METHOD = privateLookup.findVirtual(AnnotatedDynamicMethod.class,
attila@1239 573 "getTarget", MethodType.methodType(MethodHandle.class, MethodHandles.Lookup.class, LinkerServices.class));
aoqi@0 574 private static final MethodHandle GETTER_INVOKER = MethodHandles.invoker(MethodType.methodType(Object.class, Object.class));
aoqi@0 575
attila@962 576 private GuardedInvocationComponent getPropertyGetter(final CallSiteDescriptor callSiteDescriptor,
attila@962 577 final LinkerServices linkerServices, final List<String> ops) throws Exception {
aoqi@0 578 switch(callSiteDescriptor.getNameTokenCount()) {
aoqi@0 579 case 2: {
attila@963 580 // Since we can't know what kind of a getter we'll get back on different invocations, we'll just
attila@963 581 // conservatively presume Object. Note we can't just coerce to a narrower call site type as the linking
attila@963 582 // runtime might not allow coercing at that call site.
attila@963 583 final MethodType type = callSiteDescriptor.getMethodType().changeReturnType(Object.class);
aoqi@0 584 // Must have exactly two arguments: receiver and name
aoqi@0 585 assertParameterCount(callSiteDescriptor, 2);
aoqi@0 586
aoqi@0 587 // What's below is basically:
aoqi@0 588 // foldArguments(guardWithTest(isNotNull, invoke(get_handle), null|nextComponent.invocation), get_getter_handle)
aoqi@0 589 // only with a bunch of method signature adjustments. Basically, retrieve method getter
aoqi@0 590 // AnnotatedDynamicMethod; if it is non-null, invoke its "handle" field, otherwise either return null,
aoqi@0 591 // or delegate to next component's invocation.
aoqi@0 592
aoqi@0 593 final MethodHandle typedGetter = linkerServices.asType(getPropertyGetterHandle, type.changeReturnType(
aoqi@0 594 AnnotatedDynamicMethod.class));
aoqi@0 595 final MethodHandle callSiteBoundMethodGetter = MethodHandles.insertArguments(
attila@1239 596 GET_ANNOTATED_METHOD, 1, callSiteDescriptor.getLookup(), linkerServices);
aoqi@0 597 final MethodHandle callSiteBoundInvoker = MethodHandles.filterArguments(GETTER_INVOKER, 0,
aoqi@0 598 callSiteBoundMethodGetter);
attila@963 599 // Object(AnnotatedDynamicMethod, Object)->Object(AnnotatedDynamicMethod, T0)
aoqi@0 600 final MethodHandle invokeHandleTyped = linkerServices.asType(callSiteBoundInvoker,
aoqi@0 601 MethodType.methodType(type.returnType(), AnnotatedDynamicMethod.class, type.parameterType(0)));
aoqi@0 602 // Since it's in the target of a fold, drop the unnecessary second argument
attila@963 603 // Object(AnnotatedDynamicMethod, T0)->Object(AnnotatedDynamicMethod, T0, T1)
aoqi@0 604 final MethodHandle invokeHandleFolded = MethodHandles.dropArguments(invokeHandleTyped, 2,
aoqi@0 605 type.parameterType(1));
aoqi@0 606 final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor,
aoqi@0 607 linkerServices, ops);
aoqi@0 608
aoqi@0 609 final MethodHandle fallbackFolded;
aoqi@0 610 if(nextComponent == null) {
attila@963 611 // Object(AnnotatedDynamicMethod)->Object(AnnotatedDynamicMethod, T0, T1); returns constant null
aoqi@0 612 fallbackFolded = MethodHandles.dropArguments(CONSTANT_NULL_DROP_ANNOTATED_METHOD, 1,
aoqi@0 613 type.parameterList()).asType(type.insertParameterTypes(0, AnnotatedDynamicMethod.class));
aoqi@0 614 } else {
attila@963 615 // Object(T0, T1)->Object(AnnotatedDynamicMethod, T0, T1); adapts the next component's invocation to
attila@963 616 // drop the extra argument resulting from fold and to change its return type to Object.
attila@963 617 final MethodHandle nextInvocation = nextComponent.getGuardedInvocation().getInvocation();
attila@963 618 final MethodType nextType = nextInvocation.type();
attila@963 619 fallbackFolded = MethodHandles.dropArguments(nextInvocation.asType(
attila@963 620 nextType.changeReturnType(Object.class)), 0, AnnotatedDynamicMethod.class);
aoqi@0 621 }
aoqi@0 622
attila@963 623 // fold(Object(AnnotatedDynamicMethod, T0, T1), AnnotatedDynamicMethod(T0, T1))
aoqi@0 624 final MethodHandle compositeGetter = MethodHandles.foldArguments(MethodHandles.guardWithTest(
aoqi@0 625 IS_ANNOTATED_METHOD_NOT_NULL, invokeHandleFolded, fallbackFolded), typedGetter);
aoqi@0 626 if(nextComponent == null) {
aoqi@0 627 return getClassGuardedInvocationComponent(compositeGetter, type);
aoqi@0 628 }
aoqi@0 629 return nextComponent.compose(compositeGetter, getClassGuard(type), clazz, ValidationType.EXACT_CLASS);
aoqi@0 630 }
aoqi@0 631 case 3: {
aoqi@0 632 // Must have exactly one argument: receiver
aoqi@0 633 assertParameterCount(callSiteDescriptor, 1);
aoqi@0 634 // Fixed name
aoqi@0 635 final AnnotatedDynamicMethod annGetter = propertyGetters.get(callSiteDescriptor.getNameToken(
aoqi@0 636 CallSiteDescriptor.NAME_OPERAND));
aoqi@0 637 if(annGetter == null) {
aoqi@0 638 // We have no such property, always delegate to the next component operation
aoqi@0 639 return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, ops);
aoqi@0 640 }
aoqi@0 641 final MethodHandle getter = annGetter.getInvocation(callSiteDescriptor, linkerServices);
aoqi@0 642 // NOTE: since property getters (not field getters!) are no-arg, we don't have to worry about them being
aoqi@0 643 // overloaded in a subclass. Therefore, we can discover the most abstract superclass that has the
aoqi@0 644 // method, and use that as the guard with Guards.isInstance() for a more stably linked call site. If
aoqi@0 645 // we're linking against a field getter, don't make the assumption.
aoqi@0 646 // NOTE: No delegation to the next component operation if we have a property with this name, even if its
aoqi@0 647 // value is null.
aoqi@0 648 final ValidationType validationType = annGetter.validationType;
aoqi@0 649 // TODO: we aren't using the type that declares the most generic getter here!
attila@963 650 return new GuardedInvocationComponent(getter, getGuard(validationType,
attila@963 651 callSiteDescriptor.getMethodType()), clazz, validationType);
aoqi@0 652 }
aoqi@0 653 default: {
aoqi@0 654 // Can't do anything with more than 3 name components
aoqi@0 655 return null;
aoqi@0 656 }
aoqi@0 657 }
aoqi@0 658 }
aoqi@0 659
attila@962 660 private MethodHandle getGuard(final ValidationType validationType, final MethodType methodType) {
aoqi@0 661 switch(validationType) {
aoqi@0 662 case EXACT_CLASS: {
aoqi@0 663 return getClassGuard(methodType);
aoqi@0 664 }
aoqi@0 665 case INSTANCE_OF: {
aoqi@0 666 return getAssignableGuard(methodType);
aoqi@0 667 }
aoqi@0 668 case IS_ARRAY: {
aoqi@0 669 return Guards.isArray(0, methodType);
aoqi@0 670 }
aoqi@0 671 case NONE: {
aoqi@0 672 return null;
aoqi@0 673 }
aoqi@0 674 default: {
aoqi@0 675 throw new AssertionError();
aoqi@0 676 }
aoqi@0 677 }
aoqi@0 678 }
aoqi@0 679
attila@963 680 private static final MethodHandle IS_DYNAMIC_METHOD = Guards.isInstance(DynamicMethod.class,
attila@963 681 MethodType.methodType(boolean.class, Object.class));
attila@963 682 private static final MethodHandle OBJECT_IDENTITY = MethodHandles.identity(Object.class);
aoqi@0 683
attila@962 684 private GuardedInvocationComponent getMethodGetter(final CallSiteDescriptor callSiteDescriptor,
attila@962 685 final LinkerServices linkerServices, final List<String> ops) throws Exception {
attila@963 686 // The created method handle will always return a DynamicMethod (or null), but since we don't want that type to
attila@963 687 // be visible outside of this linker, declare it to return Object.
attila@963 688 final MethodType type = callSiteDescriptor.getMethodType().changeReturnType(Object.class);
aoqi@0 689 switch(callSiteDescriptor.getNameTokenCount()) {
aoqi@0 690 case 2: {
aoqi@0 691 // Must have exactly two arguments: receiver and name
aoqi@0 692 assertParameterCount(callSiteDescriptor, 2);
aoqi@0 693 final GuardedInvocationComponent nextComponent = getGuardedInvocationComponent(callSiteDescriptor,
aoqi@0 694 linkerServices, ops);
attila@963 695 if(nextComponent == null || !TypeUtilities.areAssignable(DynamicMethod.class,
attila@963 696 nextComponent.getGuardedInvocation().getInvocation().type().returnType())) {
attila@963 697 // No next component operation, or it can never produce a dynamic method; just return a component
attila@963 698 // for this operation.
aoqi@0 699 return getClassGuardedInvocationComponent(linkerServices.asType(getDynamicMethod, type), type);
aoqi@0 700 }
aoqi@0 701
aoqi@0 702 // What's below is basically:
aoqi@0 703 // foldArguments(guardWithTest(isNotNull, identity, nextComponent.invocation), getter) only with a
aoqi@0 704 // bunch of method signature adjustments. Basically, execute method getter; if it returns a non-null
aoqi@0 705 // DynamicMethod, use identity to return it, otherwise delegate to nextComponent's invocation.
aoqi@0 706
attila@963 707 final MethodHandle typedGetter = linkerServices.asType(getDynamicMethod, type);
aoqi@0 708 // Since it is part of the foldArgument() target, it will have extra args that we need to drop.
aoqi@0 709 final MethodHandle returnMethodHandle = linkerServices.asType(MethodHandles.dropArguments(
attila@963 710 OBJECT_IDENTITY, 1, type.parameterList()), type.insertParameterTypes(0, Object.class));
aoqi@0 711 final MethodHandle nextComponentInvocation = nextComponent.getGuardedInvocation().getInvocation();
attila@963 712 // The assumption is that getGuardedInvocationComponent() already asType()'d it correctly modulo the
attila@963 713 // return type.
attila@963 714 assert nextComponentInvocation.type().changeReturnType(type.returnType()).equals(type);
aoqi@0 715 // Since it is part of the foldArgument() target, we have to drop an extra arg it receives.
aoqi@0 716 final MethodHandle nextCombinedInvocation = MethodHandles.dropArguments(nextComponentInvocation, 0,
attila@963 717 Object.class);
aoqi@0 718 // Assemble it all into a fold(guard(isNotNull, identity, nextInvocation), get)
aoqi@0 719 final MethodHandle compositeGetter = MethodHandles.foldArguments(MethodHandles.guardWithTest(
attila@963 720 IS_DYNAMIC_METHOD, returnMethodHandle, nextCombinedInvocation), typedGetter);
aoqi@0 721
aoqi@0 722 return nextComponent.compose(compositeGetter, getClassGuard(type), clazz, ValidationType.EXACT_CLASS);
aoqi@0 723 }
aoqi@0 724 case 3: {
aoqi@0 725 // Must have exactly one argument: receiver
aoqi@0 726 assertParameterCount(callSiteDescriptor, 1);
aoqi@0 727 final DynamicMethod method = getDynamicMethod(callSiteDescriptor.getNameToken(
aoqi@0 728 CallSiteDescriptor.NAME_OPERAND));
aoqi@0 729 if(method == null) {
aoqi@0 730 // We have no such method, always delegate to the next component
aoqi@0 731 return getGuardedInvocationComponent(callSiteDescriptor, linkerServices, ops);
aoqi@0 732 }
aoqi@0 733 // No delegation to the next component of the composite operation; if we have a method with that name,
aoqi@0 734 // we'll always return it at this point.
aoqi@0 735 return getClassGuardedInvocationComponent(linkerServices.asType(MethodHandles.dropArguments(
attila@963 736 MethodHandles.constant(Object.class, method), 0, type.parameterType(0)), type), type);
aoqi@0 737 }
aoqi@0 738 default: {
aoqi@0 739 // Can't do anything with more than 3 name components
aoqi@0 740 return null;
aoqi@0 741 }
aoqi@0 742 }
aoqi@0 743 }
aoqi@0 744
attila@963 745 static class MethodPair {
attila@963 746 final MethodHandle method1;
attila@963 747 final MethodHandle method2;
attila@963 748
attila@963 749 MethodPair(final MethodHandle method1, final MethodHandle method2) {
attila@963 750 this.method1 = method1;
attila@963 751 this.method2 = method2;
attila@963 752 }
attila@963 753
attila@963 754 MethodHandle guardWithTest(final MethodHandle test) {
attila@963 755 return MethodHandles.guardWithTest(test, method1, method2);
attila@963 756 }
attila@963 757 }
attila@963 758
attila@963 759 static MethodPair matchReturnTypes(final MethodHandle m1, final MethodHandle m2) {
attila@963 760 final MethodType type1 = m1.type();
attila@963 761 final MethodType type2 = m2.type();
attila@963 762 final Class<?> commonRetType = TypeUtilities.getCommonLosslessConversionType(type1.returnType(),
attila@963 763 type2.returnType());
attila@963 764 return new MethodPair(
attila@963 765 m1.asType(type1.changeReturnType(commonRetType)),
attila@963 766 m2.asType(type2.changeReturnType(commonRetType)));
attila@963 767 }
attila@963 768
attila@962 769 private static void assertParameterCount(final CallSiteDescriptor descriptor, final int paramCount) {
aoqi@0 770 if(descriptor.getMethodType().parameterCount() != paramCount) {
aoqi@0 771 throw new BootstrapMethodError(descriptor.getName() + " must have exactly " + paramCount + " parameters.");
aoqi@0 772 }
aoqi@0 773 }
aoqi@0 774
aoqi@0 775 private static MethodHandle GET_PROPERTY_GETTER_HANDLE = MethodHandles.dropArguments(privateLookup.findOwnSpecial(
aoqi@0 776 "getPropertyGetterHandle", Object.class, Object.class), 1, Object.class);
aoqi@0 777 private final MethodHandle getPropertyGetterHandle = GET_PROPERTY_GETTER_HANDLE.bindTo(this);
aoqi@0 778
aoqi@0 779 /**
aoqi@0 780 * @param id the property ID
aoqi@0 781 * @return the method handle for retrieving the property, or null if the property does not exist
aoqi@0 782 */
aoqi@0 783 @SuppressWarnings("unused")
attila@962 784 private Object getPropertyGetterHandle(final Object id) {
sundar@1651 785 return propertyGetters.get(String.valueOf(id));
aoqi@0 786 }
aoqi@0 787
aoqi@0 788 // Type is MethodHandle(BeanLinker, MethodType, LinkerServices, Object, String, Object), of which the two "Object"
aoqi@0 789 // args are dropped; this makes handles with first three args conform to "Object, String, Object" though, which is
aoqi@0 790 // a typical property setter with variable name signature (target, name, value).
aoqi@0 791 private static final MethodHandle GET_PROPERTY_SETTER_HANDLE = MethodHandles.dropArguments(MethodHandles.dropArguments(
aoqi@0 792 privateLookup.findOwnSpecial("getPropertySetterHandle", MethodHandle.class, CallSiteDescriptor.class,
aoqi@0 793 LinkerServices.class, Object.class), 3, Object.class), 5, Object.class);
aoqi@0 794 // Type is MethodHandle(MethodType, LinkerServices, Object, String, Object)
aoqi@0 795 private final MethodHandle getPropertySetterHandle = GET_PROPERTY_SETTER_HANDLE.bindTo(this);
aoqi@0 796
aoqi@0 797 @SuppressWarnings("unused")
attila@962 798 private MethodHandle getPropertySetterHandle(final CallSiteDescriptor setterDescriptor, final LinkerServices linkerServices,
attila@962 799 final Object id) {
aoqi@0 800 return getDynamicMethodInvocation(setterDescriptor, linkerServices, String.valueOf(id), propertySetters);
aoqi@0 801 }
aoqi@0 802
aoqi@0 803 private static MethodHandle GET_DYNAMIC_METHOD = MethodHandles.dropArguments(privateLookup.findOwnSpecial(
attila@963 804 "getDynamicMethod", Object.class, Object.class), 1, Object.class);
aoqi@0 805 private final MethodHandle getDynamicMethod = GET_DYNAMIC_METHOD.bindTo(this);
aoqi@0 806
aoqi@0 807 @SuppressWarnings("unused")
attila@963 808 // This method is marked to return Object instead of DynamicMethod as it's used as a linking component and we don't
attila@963 809 // want to make the DynamicMethod type observable externally (e.g. as the return type of a MethodHandle returned for
attila@963 810 // "dyn:getMethod" linking).
attila@963 811 private Object getDynamicMethod(final Object name) {
aoqi@0 812 return getDynamicMethod(String.valueOf(name), methods);
aoqi@0 813 }
aoqi@0 814
aoqi@0 815 /**
aoqi@0 816 * Returns a dynamic method of the specified name.
aoqi@0 817 *
aoqi@0 818 * @param name name of the method
aoqi@0 819 * @return the dynamic method (either {@link SimpleDynamicMethod} or {@link OverloadedDynamicMethod}, or null if the
aoqi@0 820 * method with the specified name does not exist.
aoqi@0 821 */
attila@962 822 DynamicMethod getDynamicMethod(final String name) {
aoqi@0 823 return getDynamicMethod(name, methods);
aoqi@0 824 }
aoqi@0 825
aoqi@0 826 /**
aoqi@0 827 * Find the most generic superclass that declares this getter. Since getters have zero args (aside from the
aoqi@0 828 * receiver), they can't be overloaded, so we're free to link with an instanceof guard for the most generic one,
aoqi@0 829 * creating more stable call sites.
aoqi@0 830 * @param getter the getter
aoqi@0 831 * @return getter with same name, declared on the most generic superclass/interface of the declaring class
aoqi@0 832 */
attila@962 833 private static Method getMostGenericGetter(final Method getter) {
aoqi@0 834 return getMostGenericGetter(getter.getName(), getter.getReturnType(), getter.getDeclaringClass());
aoqi@0 835 }
aoqi@0 836
attila@962 837 private static Method getMostGenericGetter(final String name, final Class<?> returnType, final Class<?> declaringClass) {
aoqi@0 838 if(declaringClass == null) {
aoqi@0 839 return null;
aoqi@0 840 }
aoqi@0 841 // Prefer interfaces
attila@962 842 for(final Class<?> itf: declaringClass.getInterfaces()) {
aoqi@0 843 final Method itfGetter = getMostGenericGetter(name, returnType, itf);
aoqi@0 844 if(itfGetter != null) {
aoqi@0 845 return itfGetter;
aoqi@0 846 }
aoqi@0 847 }
aoqi@0 848 final Method superGetter = getMostGenericGetter(name, returnType, declaringClass.getSuperclass());
aoqi@0 849 if(superGetter != null) {
aoqi@0 850 return superGetter;
aoqi@0 851 }
aoqi@0 852 if(!CheckRestrictedPackage.isRestrictedClass(declaringClass)) {
aoqi@0 853 try {
aoqi@0 854 return declaringClass.getMethod(name);
attila@962 855 } catch(final NoSuchMethodException e) {
aoqi@0 856 // Intentionally ignored, meant to fall through
aoqi@0 857 }
aoqi@0 858 }
aoqi@0 859 return null;
aoqi@0 860 }
aoqi@0 861
aoqi@0 862 private static final class AnnotatedDynamicMethod {
aoqi@0 863 private final SingleDynamicMethod method;
aoqi@0 864 /*private*/ final ValidationType validationType;
aoqi@0 865
attila@962 866 AnnotatedDynamicMethod(final SingleDynamicMethod method, final ValidationType validationType) {
aoqi@0 867 this.method = method;
aoqi@0 868 this.validationType = validationType;
aoqi@0 869 }
aoqi@0 870
attila@962 871 MethodHandle getInvocation(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) {
aoqi@0 872 return method.getInvocation(callSiteDescriptor, linkerServices);
aoqi@0 873 }
aoqi@0 874
aoqi@0 875 @SuppressWarnings("unused")
attila@1239 876 MethodHandle getTarget(final MethodHandles.Lookup lookup, final LinkerServices linkerServices) {
attila@1239 877 final MethodHandle inv = linkerServices.filterInternalObjects(method.getTarget(lookup));
aoqi@0 878 assert inv != null;
aoqi@0 879 return inv;
aoqi@0 880 }
aoqi@0 881 }
aoqi@0 882 }

mercurial