1 /* 2 * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import sun.invoke.util.VerifyAccess; 29 import sun.invoke.util.Wrapper; 30 import sun.reflect.Reflection; 31 32 import java.lang.reflect.*; 33 import java.nio.ByteOrder; 34 import java.util.List; 35 import java.util.Arrays; 36 import java.util.ArrayList; 37 import java.util.Iterator; 38 import java.util.NoSuchElementException; 39 import java.util.Objects; 40 import java.util.stream.Collectors; 41 import java.util.stream.Stream; 42 43 import static java.lang.invoke.MethodHandleStatics.*; 44 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; 45 import static java.lang.invoke.MethodType.methodType; 46 47 /** 48 * This class consists exclusively of static methods that operate on or return 49 * method handles. They fall into several categories: 50 * <ul> 51 * <li>Lookup methods which help create method handles for methods and fields. 52 * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. 53 * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. 54 * </ul> 55 * <p> 56 * @author John Rose, JSR 292 EG 57 * @since 1.7 58 */ 59 public class MethodHandles { 60 MethodHandles()61 private MethodHandles() { } // do not instantiate 62 63 // Android-changed: We do not use MemberName / MethodHandleImpl. 64 // 65 // private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 66 // static { MethodHandleImpl.initStatics(); } 67 // See IMPL_LOOKUP below. 68 69 //// Method handle creation from ordinary methods. 70 71 /** 72 * Returns a {@link Lookup lookup object} with 73 * full capabilities to emulate all supported bytecode behaviors of the caller. 74 * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. 75 * Factory methods on the lookup object can create 76 * <a href="MethodHandleInfo.html#directmh">direct method handles</a> 77 * for any member that the caller has access to via bytecodes, 78 * including protected and private fields and methods. 79 * This lookup object is a <em>capability</em> which may be delegated to trusted agents. 80 * Do not store it in place where untrusted code can access it. 81 * <p> 82 * This method is caller sensitive, which means that it may return different 83 * values to different callers. 84 * <p> 85 * For any given caller class {@code C}, the lookup object returned by this call 86 * has equivalent capabilities to any lookup object 87 * supplied by the JVM to the bootstrap method of an 88 * <a href="package-summary.html#indyinsn">invokedynamic instruction</a> 89 * executing in the same caller class {@code C}. 90 * @return a lookup object for the caller of this method, with private access 91 */ 92 // Android-changed: Remove caller sensitive. 93 // @CallerSensitive lookup()94 public static Lookup lookup() { 95 return new Lookup(Reflection.getCallerClass()); 96 } 97 98 /** 99 * Returns a {@link Lookup lookup object} which is trusted minimally. 100 * It can only be used to create method handles to 101 * publicly accessible fields and methods. 102 * <p> 103 * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class} 104 * of this lookup object will be {@link java.lang.Object}. 105 * 106 * <p style="font-size:smaller;"> 107 * <em>Discussion:</em> 108 * The lookup class can be changed to any other class {@code C} using an expression of the form 109 * {@link Lookup#in publicLookup().in(C.class)}. 110 * Since all classes have equal access to public names, 111 * such a change would confer no new access rights. 112 * A public lookup object is always subject to 113 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. 114 * Also, it cannot access 115 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. 116 * @return a lookup object which is trusted minimally 117 */ publicLookup()118 public static Lookup publicLookup() { 119 return Lookup.PUBLIC_LOOKUP; 120 } 121 122 // Android-removed: Documentation related to the security manager and module checks 123 /** 124 * Returns a {@link Lookup lookup object} with full capabilities to emulate all 125 * supported bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc"> 126 * private access</a>, on a target class. 127 * @param targetClass the target class 128 * @param lookup the caller lookup object 129 * @return a lookup object for the target class, with private access 130 * @throws IllegalArgumentException if {@code targetClass} is a primitive type or array class 131 * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null} 132 * @throws IllegalAccessException is not thrown on Android 133 * @since 9 134 */ privateLookupIn(Class<?> targetClass, Lookup lookup)135 public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException { 136 // Android-removed: SecurityManager calls 137 // SecurityManager sm = System.getSecurityManager(); 138 // if (sm != null) sm.checkPermission(ACCESS_PERMISSION); 139 if (targetClass.isPrimitive()) 140 throw new IllegalArgumentException(targetClass + " is a primitive class"); 141 if (targetClass.isArray()) 142 throw new IllegalArgumentException(targetClass + " is an array class"); 143 // BEGIN Android-removed: There is no module information on Android 144 /** 145 * Module targetModule = targetClass.getModule(); 146 * Module callerModule = lookup.lookupClass().getModule(); 147 * if (!callerModule.canRead(targetModule)) 148 * throw new IllegalAccessException(callerModule + " does not read " + targetModule); 149 * if (targetModule.isNamed()) { 150 * String pn = targetClass.getPackageName(); 151 * assert pn.length() > 0 : "unnamed package cannot be in named module"; 152 * if (!targetModule.isOpen(pn, callerModule)) 153 * throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule); 154 * } 155 * if ((lookup.lookupModes() & Lookup.MODULE) == 0) 156 * throw new IllegalAccessException("lookup does not have MODULE lookup mode"); 157 * if (!callerModule.isNamed() && targetModule.isNamed()) { 158 * IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger(); 159 * if (logger != null) { 160 * logger.logIfOpenedForIllegalAccess(lookup, targetClass); 161 * } 162 * } 163 */ 164 // END Android-removed: There is no module information on Android 165 return new Lookup(targetClass); 166 } 167 168 169 /** 170 * Performs an unchecked "crack" of a 171 * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. 172 * The result is as if the user had obtained a lookup object capable enough 173 * to crack the target method handle, called 174 * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} 175 * on the target to obtain its symbolic reference, and then called 176 * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} 177 * to resolve the symbolic reference to a member. 178 * <p> 179 * If there is a security manager, its {@code checkPermission} method 180 * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. 181 * @param <T> the desired type of the result, either {@link Member} or a subtype 182 * @param target a direct method handle to crack into symbolic reference components 183 * @param expected a class object representing the desired result type {@code T} 184 * @return a reference to the method, constructor, or field object 185 * @exception SecurityException if the caller is not privileged to call {@code setAccessible} 186 * @exception NullPointerException if either argument is {@code null} 187 * @exception IllegalArgumentException if the target is not a direct method handle 188 * @exception ClassCastException if the member is not of the expected type 189 * @since 1.8 190 */ 191 public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target)192 reflectAs(Class<T> expected, MethodHandle target) { 193 MethodHandleImpl directTarget = getMethodHandleImpl(target); 194 // Given that this is specified to be an "unchecked" crack, we can directly allocate 195 // a member from the underlying ArtField / Method and bypass all associated access checks. 196 return expected.cast(directTarget.getMemberInternal()); 197 } 198 199 /** 200 * A <em>lookup object</em> is a factory for creating method handles, 201 * when the creation requires access checking. 202 * Method handles do not perform 203 * access checks when they are called, but rather when they are created. 204 * Therefore, method handle access 205 * restrictions must be enforced when a method handle is created. 206 * The caller class against which those restrictions are enforced 207 * is known as the {@linkplain #lookupClass lookup class}. 208 * <p> 209 * A lookup class which needs to create method handles will call 210 * {@link #lookup MethodHandles.lookup} to create a factory for itself. 211 * When the {@code Lookup} factory object is created, the identity of the lookup class is 212 * determined, and securely stored in the {@code Lookup} object. 213 * The lookup class (or its delegates) may then use factory methods 214 * on the {@code Lookup} object to create method handles for access-checked members. 215 * This includes all methods, constructors, and fields which are allowed to the lookup class, 216 * even private ones. 217 * 218 * <h1><a name="lookups"></a>Lookup Factory Methods</h1> 219 * The factory methods on a {@code Lookup} object correspond to all major 220 * use cases for methods, constructors, and fields. 221 * Each method handle created by a factory method is the functional 222 * equivalent of a particular <em>bytecode behavior</em>. 223 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.) 224 * Here is a summary of the correspondence between these factory methods and 225 * the behavior the resulting method handles: 226 * <table border=1 cellpadding=5 summary="lookup method behaviors"> 227 * <tr> 228 * <th><a name="equiv"></a>lookup expression</th> 229 * <th>member</th> 230 * <th>bytecode behavior</th> 231 * </tr> 232 * <tr> 233 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> 234 * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> 235 * </tr> 236 * <tr> 237 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> 238 * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td> 239 * </tr> 240 * <tr> 241 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> 242 * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> 243 * </tr> 244 * <tr> 245 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> 246 * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> 247 * </tr> 248 * <tr> 249 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> 250 * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> 251 * </tr> 252 * <tr> 253 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> 254 * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> 255 * </tr> 256 * <tr> 257 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> 258 * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> 259 * </tr> 260 * <tr> 261 * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> 262 * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> 263 * </tr> 264 * <tr> 265 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> 266 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> 267 * </tr> 268 * <tr> 269 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> 270 * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> 271 * </tr> 272 * <tr> 273 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 274 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 275 * </tr> 276 * <tr> 277 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> 278 * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> 279 * </tr> 280 * <tr> 281 * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> 282 * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> 283 * </tr> 284 * </table> 285 * 286 * Here, the type {@code C} is the class or interface being searched for a member, 287 * documented as a parameter named {@code refc} in the lookup methods. 288 * The method type {@code MT} is composed from the return type {@code T} 289 * and the sequence of argument types {@code A*}. 290 * The constructor also has a sequence of argument types {@code A*} and 291 * is deemed to return the newly-created object of type {@code C}. 292 * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. 293 * The formal parameter {@code this} stands for the self-reference of type {@code C}; 294 * if it is present, it is always the leading argument to the method handle invocation. 295 * (In the case of some {@code protected} members, {@code this} may be 296 * restricted in type to the lookup class; see below.) 297 * The name {@code arg} stands for all the other method handle arguments. 298 * In the code examples for the Core Reflection API, the name {@code thisOrNull} 299 * stands for a null reference if the accessed method or field is static, 300 * and {@code this} otherwise. 301 * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand 302 * for reflective objects corresponding to the given members. 303 * <p> 304 * In cases where the given member is of variable arity (i.e., a method or constructor) 305 * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. 306 * In all other cases, the returned method handle will be of fixed arity. 307 * <p style="font-size:smaller;"> 308 * <em>Discussion:</em> 309 * The equivalence between looked-up method handles and underlying 310 * class members and bytecode behaviors 311 * can break down in a few ways: 312 * <ul style="font-size:smaller;"> 313 * <li>If {@code C} is not symbolically accessible from the lookup class's loader, 314 * the lookup can still succeed, even when there is no equivalent 315 * Java expression or bytecoded constant. 316 * <li>Likewise, if {@code T} or {@code MT} 317 * is not symbolically accessible from the lookup class's loader, 318 * the lookup can still succeed. 319 * For example, lookups for {@code MethodHandle.invokeExact} and 320 * {@code MethodHandle.invoke} will always succeed, regardless of requested type. 321 * <li>If there is a security manager installed, it can forbid the lookup 322 * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). 323 * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} 324 * constant is not subject to security manager checks. 325 * <li>If the looked-up method has a 326 * <a href="MethodHandle.html#maxarity">very large arity</a>, 327 * the method handle creation may fail, due to the method handle 328 * type having too many parameters. 329 * </ul> 330 * 331 * <h1><a name="access"></a>Access checking</h1> 332 * Access checks are applied in the factory methods of {@code Lookup}, 333 * when a method handle is created. 334 * This is a key difference from the Core Reflection API, since 335 * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 336 * performs access checking against every caller, on every call. 337 * <p> 338 * All access checks start from a {@code Lookup} object, which 339 * compares its recorded lookup class against all requests to 340 * create method handles. 341 * A single {@code Lookup} object can be used to create any number 342 * of access-checked method handles, all checked against a single 343 * lookup class. 344 * <p> 345 * A {@code Lookup} object can be shared with other trusted code, 346 * such as a metaobject protocol. 347 * A shared {@code Lookup} object delegates the capability 348 * to create method handles on private members of the lookup class. 349 * Even if privileged code uses the {@code Lookup} object, 350 * the access checking is confined to the privileges of the 351 * original lookup class. 352 * <p> 353 * A lookup can fail, because 354 * the containing class is not accessible to the lookup class, or 355 * because the desired class member is missing, or because the 356 * desired class member is not accessible to the lookup class, or 357 * because the lookup object is not trusted enough to access the member. 358 * In any of these cases, a {@code ReflectiveOperationException} will be 359 * thrown from the attempted lookup. The exact class will be one of 360 * the following: 361 * <ul> 362 * <li>NoSuchMethodException — if a method is requested but does not exist 363 * <li>NoSuchFieldException — if a field is requested but does not exist 364 * <li>IllegalAccessException — if the member exists but an access check fails 365 * </ul> 366 * <p> 367 * In general, the conditions under which a method handle may be 368 * looked up for a method {@code M} are no more restrictive than the conditions 369 * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. 370 * Where the JVM would raise exceptions like {@code NoSuchMethodError}, 371 * a method handle lookup will generally raise a corresponding 372 * checked exception, such as {@code NoSuchMethodException}. 373 * And the effect of invoking the method handle resulting from the lookup 374 * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> 375 * to executing the compiled, verified, and resolved call to {@code M}. 376 * The same point is true of fields and constructors. 377 * <p style="font-size:smaller;"> 378 * <em>Discussion:</em> 379 * Access checks only apply to named and reflected methods, 380 * constructors, and fields. 381 * Other method handle creation methods, such as 382 * {@link MethodHandle#asType MethodHandle.asType}, 383 * do not require any access checks, and are used 384 * independently of any {@code Lookup} object. 385 * <p> 386 * If the desired member is {@code protected}, the usual JVM rules apply, 387 * including the requirement that the lookup class must be either be in the 388 * same package as the desired member, or must inherit that member. 389 * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) 390 * In addition, if the desired member is a non-static field or method 391 * in a different package, the resulting method handle may only be applied 392 * to objects of the lookup class or one of its subclasses. 393 * This requirement is enforced by narrowing the type of the leading 394 * {@code this} parameter from {@code C} 395 * (which will necessarily be a superclass of the lookup class) 396 * to the lookup class itself. 397 * <p> 398 * The JVM imposes a similar requirement on {@code invokespecial} instruction, 399 * that the receiver argument must match both the resolved method <em>and</em> 400 * the current class. Again, this requirement is enforced by narrowing the 401 * type of the leading parameter to the resulting method handle. 402 * (See the Java Virtual Machine Specification, section 4.10.1.9.) 403 * <p> 404 * The JVM represents constructors and static initializer blocks as internal methods 405 * with special names ({@code "<init>"} and {@code "<clinit>"}). 406 * The internal syntax of invocation instructions allows them to refer to such internal 407 * methods as if they were normal methods, but the JVM bytecode verifier rejects them. 408 * A lookup of such an internal method will produce a {@code NoSuchMethodException}. 409 * <p> 410 * In some cases, access between nested classes is obtained by the Java compiler by creating 411 * an wrapper method to access a private method of another class 412 * in the same top-level declaration. 413 * For example, a nested class {@code C.D} 414 * can access private members within other related classes such as 415 * {@code C}, {@code C.D.E}, or {@code C.B}, 416 * but the Java compiler may need to generate wrapper methods in 417 * those related classes. In such cases, a {@code Lookup} object on 418 * {@code C.E} would be unable to those private members. 419 * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, 420 * which can transform a lookup on {@code C.E} into one on any of those other 421 * classes, without special elevation of privilege. 422 * <p> 423 * The accesses permitted to a given lookup object may be limited, 424 * according to its set of {@link #lookupModes lookupModes}, 425 * to a subset of members normally accessible to the lookup class. 426 * For example, the {@link #publicLookup publicLookup} 427 * method produces a lookup object which is only allowed to access 428 * public members in public classes. 429 * The caller sensitive method {@link #lookup lookup} 430 * produces a lookup object with full capabilities relative to 431 * its caller class, to emulate all supported bytecode behaviors. 432 * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object 433 * with fewer access modes than the original lookup object. 434 * 435 * <p style="font-size:smaller;"> 436 * <a name="privacc"></a> 437 * <em>Discussion of private access:</em> 438 * We say that a lookup has <em>private access</em> 439 * if its {@linkplain #lookupModes lookup modes} 440 * include the possibility of accessing {@code private} members. 441 * As documented in the relevant methods elsewhere, 442 * only lookups with private access possess the following capabilities: 443 * <ul style="font-size:smaller;"> 444 * <li>access private fields, methods, and constructors of the lookup class 445 * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, 446 * such as {@code Class.forName} 447 * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions 448 * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> 449 * for classes accessible to the lookup class 450 * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes 451 * within the same package member 452 * </ul> 453 * <p style="font-size:smaller;"> 454 * Each of these permissions is a consequence of the fact that a lookup object 455 * with private access can be securely traced back to an originating class, 456 * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions 457 * can be reliably determined and emulated by method handles. 458 * 459 * <h1><a name="secmgr"></a>Security manager interactions</h1> 460 * Although bytecode instructions can only refer to classes in 461 * a related class loader, this API can search for methods in any 462 * class, as long as a reference to its {@code Class} object is 463 * available. Such cross-loader references are also possible with the 464 * Core Reflection API, and are impossible to bytecode instructions 465 * such as {@code invokestatic} or {@code getfield}. 466 * There is a {@linkplain java.lang.SecurityManager security manager API} 467 * to allow applications to check such cross-loader references. 468 * These checks apply to both the {@code MethodHandles.Lookup} API 469 * and the Core Reflection API 470 * (as found on {@link java.lang.Class Class}). 471 * <p> 472 * If a security manager is present, member lookups are subject to 473 * additional checks. 474 * From one to three calls are made to the security manager. 475 * Any of these calls can refuse access by throwing a 476 * {@link java.lang.SecurityException SecurityException}. 477 * Define {@code smgr} as the security manager, 478 * {@code lookc} as the lookup class of the current lookup object, 479 * {@code refc} as the containing class in which the member 480 * is being sought, and {@code defc} as the class in which the 481 * member is actually defined. 482 * The value {@code lookc} is defined as <em>not present</em> 483 * if the current lookup object does not have 484 * <a href="MethodHandles.Lookup.html#privacc">private access</a>. 485 * The calls are made according to the following rules: 486 * <ul> 487 * <li><b>Step 1:</b> 488 * If {@code lookc} is not present, or if its class loader is not 489 * the same as or an ancestor of the class loader of {@code refc}, 490 * then {@link SecurityManager#checkPackageAccess 491 * smgr.checkPackageAccess(refcPkg)} is called, 492 * where {@code refcPkg} is the package of {@code refc}. 493 * <li><b>Step 2:</b> 494 * If the retrieved member is not public and 495 * {@code lookc} is not present, then 496 * {@link SecurityManager#checkPermission smgr.checkPermission} 497 * with {@code RuntimePermission("accessDeclaredMembers")} is called. 498 * <li><b>Step 3:</b> 499 * If the retrieved member is not public, 500 * and if {@code lookc} is not present, 501 * and if {@code defc} and {@code refc} are different, 502 * then {@link SecurityManager#checkPackageAccess 503 * smgr.checkPackageAccess(defcPkg)} is called, 504 * where {@code defcPkg} is the package of {@code defc}. 505 * </ul> 506 * Security checks are performed after other access checks have passed. 507 * Therefore, the above rules presuppose a member that is public, 508 * or else that is being accessed from a lookup class that has 509 * rights to access the member. 510 * 511 * <h1><a name="callsens"></a>Caller sensitive methods</h1> 512 * A small number of Java methods have a special property called caller sensitivity. 513 * A <em>caller-sensitive</em> method can behave differently depending on the 514 * identity of its immediate caller. 515 * <p> 516 * If a method handle for a caller-sensitive method is requested, 517 * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, 518 * but they take account of the lookup class in a special way. 519 * The resulting method handle behaves as if it were called 520 * from an instruction contained in the lookup class, 521 * so that the caller-sensitive method detects the lookup class. 522 * (By contrast, the invoker of the method handle is disregarded.) 523 * Thus, in the case of caller-sensitive methods, 524 * different lookup classes may give rise to 525 * differently behaving method handles. 526 * <p> 527 * In cases where the lookup object is 528 * {@link #publicLookup publicLookup()}, 529 * or some other lookup object without 530 * <a href="MethodHandles.Lookup.html#privacc">private access</a>, 531 * the lookup class is disregarded. 532 * In such cases, no caller-sensitive method handle can be created, 533 * access is forbidden, and the lookup fails with an 534 * {@code IllegalAccessException}. 535 * <p style="font-size:smaller;"> 536 * <em>Discussion:</em> 537 * For example, the caller-sensitive method 538 * {@link java.lang.Class#forName(String) Class.forName(x)} 539 * can return varying classes or throw varying exceptions, 540 * depending on the class loader of the class that calls it. 541 * A public lookup of {@code Class.forName} will fail, because 542 * there is no reasonable way to determine its bytecode behavior. 543 * <p style="font-size:smaller;"> 544 * If an application caches method handles for broad sharing, 545 * it should use {@code publicLookup()} to create them. 546 * If there is a lookup of {@code Class.forName}, it will fail, 547 * and the application must take appropriate action in that case. 548 * It may be that a later lookup, perhaps during the invocation of a 549 * bootstrap method, can incorporate the specific identity 550 * of the caller, making the method accessible. 551 * <p style="font-size:smaller;"> 552 * The function {@code MethodHandles.lookup} is caller sensitive 553 * so that there can be a secure foundation for lookups. 554 * Nearly all other methods in the JSR 292 API rely on lookup 555 * objects to check access requests. 556 */ 557 // Android-changed: Change link targets from MethodHandles#[public]Lookup to 558 // #[public]Lookup to work around complaints from javadoc. 559 public static final 560 class Lookup { 561 /** The class on behalf of whom the lookup is being performed. */ 562 /* @NonNull */ private final Class<?> lookupClass; 563 564 /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ 565 private final int allowedModes; 566 567 /** A single-bit mask representing {@code public} access, 568 * which may contribute to the result of {@link #lookupModes lookupModes}. 569 * The value, {@code 0x01}, happens to be the same as the value of the 570 * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. 571 */ 572 public static final int PUBLIC = Modifier.PUBLIC; 573 574 /** A single-bit mask representing {@code private} access, 575 * which may contribute to the result of {@link #lookupModes lookupModes}. 576 * The value, {@code 0x02}, happens to be the same as the value of the 577 * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. 578 */ 579 public static final int PRIVATE = Modifier.PRIVATE; 580 581 /** A single-bit mask representing {@code protected} access, 582 * which may contribute to the result of {@link #lookupModes lookupModes}. 583 * The value, {@code 0x04}, happens to be the same as the value of the 584 * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. 585 */ 586 public static final int PROTECTED = Modifier.PROTECTED; 587 588 /** A single-bit mask representing {@code package} access (default access), 589 * which may contribute to the result of {@link #lookupModes lookupModes}. 590 * The value is {@code 0x08}, which does not correspond meaningfully to 591 * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. 592 */ 593 public static final int PACKAGE = Modifier.STATIC; 594 595 private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE); 596 597 // Android-note: Android has no notion of a trusted lookup. If required, such lookups 598 // are performed by the runtime. As a result, we always use lookupClass, which will always 599 // be non-null in our implementation. 600 // 601 // private static final int TRUSTED = -1; 602 fixmods(int mods)603 private static int fixmods(int mods) { 604 mods &= (ALL_MODES - PACKAGE); 605 return (mods != 0) ? mods : PACKAGE; 606 } 607 608 /** Tells which class is performing the lookup. It is this class against 609 * which checks are performed for visibility and access permissions. 610 * <p> 611 * The class implies a maximum level of access permission, 612 * but the permissions may be additionally limited by the bitmask 613 * {@link #lookupModes lookupModes}, which controls whether non-public members 614 * can be accessed. 615 * @return the lookup class, on behalf of which this lookup object finds members 616 */ lookupClass()617 public Class<?> lookupClass() { 618 return lookupClass; 619 } 620 621 /** Tells which access-protection classes of members this lookup object can produce. 622 * The result is a bit-mask of the bits 623 * {@linkplain #PUBLIC PUBLIC (0x01)}, 624 * {@linkplain #PRIVATE PRIVATE (0x02)}, 625 * {@linkplain #PROTECTED PROTECTED (0x04)}, 626 * and {@linkplain #PACKAGE PACKAGE (0x08)}. 627 * <p> 628 * A freshly-created lookup object 629 * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} 630 * has all possible bits set, since the caller class can access all its own members. 631 * A lookup object on a new lookup class 632 * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} 633 * may have some mode bits set to zero. 634 * The purpose of this is to restrict access via the new lookup object, 635 * so that it can access only names which can be reached by the original 636 * lookup object, and also by the new lookup class. 637 * @return the lookup modes, which limit the kinds of access performed by this lookup object 638 */ lookupModes()639 public int lookupModes() { 640 return allowedModes & ALL_MODES; 641 } 642 643 /** Embody the current class (the lookupClass) as a lookup class 644 * for method handle creation. 645 * Must be called by from a method in this package, 646 * which in turn is called by a method not in this package. 647 */ Lookup(Class<?> lookupClass)648 Lookup(Class<?> lookupClass) { 649 this(lookupClass, ALL_MODES); 650 // make sure we haven't accidentally picked up a privileged class: 651 checkUnprivilegedlookupClass(lookupClass, ALL_MODES); 652 } 653 Lookup(Class<?> lookupClass, int allowedModes)654 private Lookup(Class<?> lookupClass, int allowedModes) { 655 this.lookupClass = lookupClass; 656 this.allowedModes = allowedModes; 657 } 658 659 /** 660 * Creates a lookup on the specified new lookup class. 661 * The resulting object will report the specified 662 * class as its own {@link #lookupClass lookupClass}. 663 * <p> 664 * However, the resulting {@code Lookup} object is guaranteed 665 * to have no more access capabilities than the original. 666 * In particular, access capabilities can be lost as follows:<ul> 667 * <li>If the new lookup class differs from the old one, 668 * protected members will not be accessible by virtue of inheritance. 669 * (Protected members may continue to be accessible because of package sharing.) 670 * <li>If the new lookup class is in a different package 671 * than the old one, protected and default (package) members will not be accessible. 672 * <li>If the new lookup class is not within the same package member 673 * as the old one, private members will not be accessible. 674 * <li>If the new lookup class is not accessible to the old lookup class, 675 * then no members, not even public members, will be accessible. 676 * (In all other cases, public members will continue to be accessible.) 677 * </ul> 678 * 679 * @param requestedLookupClass the desired lookup class for the new lookup object 680 * @return a lookup object which reports the desired lookup class 681 * @throws NullPointerException if the argument is null 682 */ in(Class<?> requestedLookupClass)683 public Lookup in(Class<?> requestedLookupClass) { 684 requestedLookupClass.getClass(); // null check 685 // Android-changed: There's no notion of a trusted lookup. 686 // if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all 687 // return new Lookup(requestedLookupClass, ALL_MODES); 688 689 if (requestedLookupClass == this.lookupClass) 690 return this; // keep same capabilities 691 int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); 692 if ((newModes & PACKAGE) != 0 693 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { 694 newModes &= ~(PACKAGE|PRIVATE); 695 } 696 // Allow nestmate lookups to be created without special privilege: 697 if ((newModes & PRIVATE) != 0 698 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { 699 newModes &= ~PRIVATE; 700 } 701 if ((newModes & PUBLIC) != 0 702 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { 703 // The requested class it not accessible from the lookup class. 704 // No permissions. 705 newModes = 0; 706 } 707 checkUnprivilegedlookupClass(requestedLookupClass, newModes); 708 return new Lookup(requestedLookupClass, newModes); 709 } 710 711 // Make sure outer class is initialized first. 712 // 713 // Android-changed: Removed unnecessary reference to IMPL_NAMES. 714 // static { IMPL_NAMES.getClass(); } 715 716 /** Version of lookup which is trusted minimally. 717 * It can only be used to create method handles to 718 * publicly accessible members. 719 */ 720 static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, PUBLIC); 721 722 /** Package-private version of lookup which is trusted. */ 723 static final Lookup IMPL_LOOKUP = new Lookup(Object.class, ALL_MODES); 724 checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes)725 private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) { 726 String name = lookupClass.getName(); 727 if (name.startsWith("java.lang.invoke.")) 728 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); 729 730 // For caller-sensitive MethodHandles.lookup() 731 // disallow lookup more restricted packages 732 // 733 // Android-changed: The bootstrap classloader isn't null. 734 if (allowedModes == ALL_MODES && 735 lookupClass.getClassLoader() == Object.class.getClassLoader()) { 736 if ((name.startsWith("java.") 737 && !name.startsWith("java.util.concurrent.") 738 && !name.equals("java.lang.Thread")) || 739 (name.startsWith("sun.") 740 && !name.startsWith("sun.invoke.") 741 && !name.equals("sun.reflect.ReflectionFactory"))) { 742 throw newIllegalArgumentException("illegal lookupClass: " + lookupClass); 743 } 744 } 745 } 746 747 /** 748 * Displays the name of the class from which lookups are to be made. 749 * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) 750 * If there are restrictions on the access permitted to this lookup, 751 * this is indicated by adding a suffix to the class name, consisting 752 * of a slash and a keyword. The keyword represents the strongest 753 * allowed access, and is chosen as follows: 754 * <ul> 755 * <li>If no access is allowed, the suffix is "/noaccess". 756 * <li>If only public access is allowed, the suffix is "/public". 757 * <li>If only public and package access are allowed, the suffix is "/package". 758 * <li>If only public, package, and private access are allowed, the suffix is "/private". 759 * </ul> 760 * If none of the above cases apply, it is the case that full 761 * access (public, package, private, and protected) is allowed. 762 * In this case, no suffix is added. 763 * This is true only of an object obtained originally from 764 * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. 765 * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} 766 * always have restricted access, and will display a suffix. 767 * <p> 768 * (It may seem strange that protected access should be 769 * stronger than private access. Viewed independently from 770 * package access, protected access is the first to be lost, 771 * because it requires a direct subclass relationship between 772 * caller and callee.) 773 * @see #in 774 */ 775 @Override toString()776 public String toString() { 777 String cname = lookupClass.getName(); 778 switch (allowedModes) { 779 case 0: // no privileges 780 return cname + "/noaccess"; 781 case PUBLIC: 782 return cname + "/public"; 783 case PUBLIC|PACKAGE: 784 return cname + "/package"; 785 case ALL_MODES & ~PROTECTED: 786 return cname + "/private"; 787 case ALL_MODES: 788 return cname; 789 // Android-changed: No support for TRUSTED callers. 790 // case TRUSTED: 791 // return "/trusted"; // internal only; not exported 792 default: // Should not happen, but it's a bitfield... 793 cname = cname + "/" + Integer.toHexString(allowedModes); 794 assert(false) : cname; 795 return cname; 796 } 797 } 798 799 /** 800 * Produces a method handle for a static method. 801 * The type of the method handle will be that of the method. 802 * (Since static methods do not take receivers, there is no 803 * additional receiver argument inserted into the method handle type, 804 * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) 805 * The method and all its argument types must be accessible to the lookup object. 806 * <p> 807 * The returned method handle will have 808 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 809 * the method's variable arity modifier bit ({@code 0x0080}) is set. 810 * <p> 811 * If the returned method handle is invoked, the method's class will 812 * be initialized, if it has not already been initialized. 813 * <p><b>Example:</b> 814 * <blockquote><pre>{@code 815 import static java.lang.invoke.MethodHandles.*; 816 import static java.lang.invoke.MethodType.*; 817 ... 818 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, 819 "asList", methodType(List.class, Object[].class)); 820 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); 821 * }</pre></blockquote> 822 * @param refc the class from which the method is accessed 823 * @param name the name of the method 824 * @param type the type of the method 825 * @return the desired method handle 826 * @throws NoSuchMethodException if the method does not exist 827 * @throws IllegalAccessException if access checking fails, 828 * or if the method is not {@code static}, 829 * or if the method's variable arity modifier bit 830 * is set and {@code asVarargsCollector} fails 831 * @exception SecurityException if a security manager is present and it 832 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 833 * @throws NullPointerException if any argument is null 834 */ 835 public findStatic(Class<?> refc, String name, MethodType type)836 MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 837 Method method = refc.getDeclaredMethod(name, type.ptypes()); 838 final int modifiers = method.getModifiers(); 839 if (!Modifier.isStatic(modifiers)) { 840 throw new IllegalAccessException("Method" + method + " is not static"); 841 } 842 checkReturnType(method, type); 843 checkAccess(refc, method.getDeclaringClass(), modifiers, method.getName()); 844 return createMethodHandle(method, MethodHandle.INVOKE_STATIC, type); 845 } 846 findVirtualForMH(String name, MethodType type)847 private MethodHandle findVirtualForMH(String name, MethodType type) { 848 // these names require special lookups because of the implicit MethodType argument 849 if ("invoke".equals(name)) 850 return invoker(type); 851 if ("invokeExact".equals(name)) 852 return exactInvoker(type); 853 return null; 854 } 855 findVirtualForVH(String name, MethodType type)856 private MethodHandle findVirtualForVH(String name, MethodType type) { 857 VarHandle.AccessMode accessMode; 858 try { 859 accessMode = VarHandle.AccessMode.valueFromMethodName(name); 860 } catch (IllegalArgumentException e) { 861 return null; 862 } 863 return varHandleInvoker(accessMode, type); 864 } 865 createMethodHandle(Method method, int handleKind, MethodType methodType)866 private static MethodHandle createMethodHandle(Method method, int handleKind, 867 MethodType methodType) { 868 MethodHandle mh = new MethodHandleImpl(method.getArtMethod(), handleKind, methodType); 869 if (method.isVarArgs()) { 870 return new Transformers.VarargsCollector(mh); 871 } else { 872 return mh; 873 } 874 } 875 876 /** 877 * Produces a method handle for a virtual method. 878 * The type of the method handle will be that of the method, 879 * with the receiver type (usually {@code refc}) prepended. 880 * The method and all its argument types must be accessible to the lookup object. 881 * <p> 882 * When called, the handle will treat the first argument as a receiver 883 * and dispatch on the receiver's type to determine which method 884 * implementation to enter. 885 * (The dispatching action is identical with that performed by an 886 * {@code invokevirtual} or {@code invokeinterface} instruction.) 887 * <p> 888 * The first argument will be of type {@code refc} if the lookup 889 * class has full privileges to access the member. Otherwise 890 * the member must be {@code protected} and the first argument 891 * will be restricted in type to the lookup class. 892 * <p> 893 * The returned method handle will have 894 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 895 * the method's variable arity modifier bit ({@code 0x0080}) is set. 896 * <p> 897 * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} 898 * instructions and method handles produced by {@code findVirtual}, 899 * if the class is {@code MethodHandle} and the name string is 900 * {@code invokeExact} or {@code invoke}, the resulting 901 * method handle is equivalent to one produced by 902 * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or 903 * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} 904 * with the same {@code type} argument. 905 * 906 * <b>Example:</b> 907 * <blockquote><pre>{@code 908 import static java.lang.invoke.MethodHandles.*; 909 import static java.lang.invoke.MethodType.*; 910 ... 911 MethodHandle MH_concat = publicLookup().findVirtual(String.class, 912 "concat", methodType(String.class, String.class)); 913 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, 914 "hashCode", methodType(int.class)); 915 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, 916 "hashCode", methodType(int.class)); 917 assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); 918 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); 919 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); 920 // interface method: 921 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, 922 "subSequence", methodType(CharSequence.class, int.class, int.class)); 923 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); 924 // constructor "internal method" must be accessed differently: 925 MethodType MT_newString = methodType(void.class); //()V for new String() 926 try { assertEquals("impossible", lookup() 927 .findVirtual(String.class, "<init>", MT_newString)); 928 } catch (NoSuchMethodException ex) { } // OK 929 MethodHandle MH_newString = publicLookup() 930 .findConstructor(String.class, MT_newString); 931 assertEquals("", (String) MH_newString.invokeExact()); 932 * }</pre></blockquote> 933 * 934 * @param refc the class or interface from which the method is accessed 935 * @param name the name of the method 936 * @param type the type of the method, with the receiver argument omitted 937 * @return the desired method handle 938 * @throws NoSuchMethodException if the method does not exist 939 * @throws IllegalAccessException if access checking fails, 940 * or if the method is {@code static} 941 * or if the method's variable arity modifier bit 942 * is set and {@code asVarargsCollector} fails 943 * @exception SecurityException if a security manager is present and it 944 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 945 * @throws NullPointerException if any argument is null 946 */ findVirtual(Class<?> refc, String name, MethodType type)947 public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 948 // Special case : when we're looking up a virtual method on the MethodHandles class 949 // itself, we can return one of our specialized invokers. 950 if (refc == MethodHandle.class) { 951 MethodHandle mh = findVirtualForMH(name, type); 952 if (mh != null) { 953 return mh; 954 } 955 } else if (refc == VarHandle.class) { 956 // Returns an non-exact invoker. 957 MethodHandle mh = findVirtualForVH(name, type); 958 if (mh != null) { 959 return mh; 960 } 961 } 962 963 Method method = refc.getInstanceMethod(name, type.ptypes()); 964 if (method == null) { 965 // This is pretty ugly and a consequence of the MethodHandles API. We have to throw 966 // an IAE and not an NSME if the method exists but is static (even though the RI's 967 // IAE has a message that says "no such method"). We confine the ugliness and 968 // slowness to the failure case, and allow getInstanceMethod to remain fairly 969 // general. 970 try { 971 Method m = refc.getDeclaredMethod(name, type.ptypes()); 972 if (Modifier.isStatic(m.getModifiers())) { 973 throw new IllegalAccessException("Method" + m + " is static"); 974 } 975 } catch (NoSuchMethodException ignored) { 976 } 977 978 throw new NoSuchMethodException(name + " " + Arrays.toString(type.ptypes())); 979 } 980 checkReturnType(method, type); 981 982 // We have a valid method, perform access checks. 983 checkAccess(refc, method.getDeclaringClass(), method.getModifiers(), method.getName()); 984 985 // Insert the leading reference parameter. 986 MethodType handleType = type.insertParameterTypes(0, refc); 987 return createMethodHandle(method, MethodHandle.INVOKE_VIRTUAL, handleType); 988 } 989 990 /** 991 * Produces a method handle which creates an object and initializes it, using 992 * the constructor of the specified type. 993 * The parameter types of the method handle will be those of the constructor, 994 * while the return type will be a reference to the constructor's class. 995 * The constructor and all its argument types must be accessible to the lookup object. 996 * <p> 997 * The requested type must have a return type of {@code void}. 998 * (This is consistent with the JVM's treatment of constructor type descriptors.) 999 * <p> 1000 * The returned method handle will have 1001 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1002 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 1003 * <p> 1004 * If the returned method handle is invoked, the constructor's class will 1005 * be initialized, if it has not already been initialized. 1006 * <p><b>Example:</b> 1007 * <blockquote><pre>{@code 1008 import static java.lang.invoke.MethodHandles.*; 1009 import static java.lang.invoke.MethodType.*; 1010 ... 1011 MethodHandle MH_newArrayList = publicLookup().findConstructor( 1012 ArrayList.class, methodType(void.class, Collection.class)); 1013 Collection orig = Arrays.asList("x", "y"); 1014 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); 1015 assert(orig != copy); 1016 assertEquals(orig, copy); 1017 // a variable-arity constructor: 1018 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( 1019 ProcessBuilder.class, methodType(void.class, String[].class)); 1020 ProcessBuilder pb = (ProcessBuilder) 1021 MH_newProcessBuilder.invoke("x", "y", "z"); 1022 assertEquals("[x, y, z]", pb.command().toString()); 1023 * }</pre></blockquote> 1024 * @param refc the class or interface from which the method is accessed 1025 * @param type the type of the method, with the receiver argument omitted, and a void return type 1026 * @return the desired method handle 1027 * @throws NoSuchMethodException if the constructor does not exist 1028 * @throws IllegalAccessException if access checking fails 1029 * or if the method's variable arity modifier bit 1030 * is set and {@code asVarargsCollector} fails 1031 * @exception SecurityException if a security manager is present and it 1032 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1033 * @throws NullPointerException if any argument is null 1034 */ findConstructor(Class<?> refc, MethodType type)1035 public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1036 if (refc.isArray()) { 1037 throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); 1038 } 1039 // The queried |type| is (PT1,PT2,..)V 1040 Constructor constructor = refc.getDeclaredConstructor(type.ptypes()); 1041 if (constructor == null) { 1042 throw new NoSuchMethodException( 1043 "No constructor for " + constructor.getDeclaringClass() + " matching " + type); 1044 } 1045 checkAccess(refc, constructor.getDeclaringClass(), constructor.getModifiers(), 1046 constructor.getName()); 1047 1048 return createMethodHandleForConstructor(constructor); 1049 } 1050 createMethodHandleForConstructor(Constructor constructor)1051 private MethodHandle createMethodHandleForConstructor(Constructor constructor) { 1052 Class<?> refc = constructor.getDeclaringClass(); 1053 MethodType constructorType = 1054 MethodType.methodType(refc, constructor.getParameterTypes()); 1055 MethodHandle mh; 1056 if (refc == String.class) { 1057 // String constructors have optimized StringFactory methods 1058 // that matches returned type. These factory methods combine the 1059 // memory allocation and initialization calls for String objects. 1060 mh = new MethodHandleImpl(constructor.getArtMethod(), MethodHandle.INVOKE_DIRECT, 1061 constructorType); 1062 } else { 1063 // Constructors for all other classes use a Construct transformer to perform 1064 // their memory allocation and call to <init>. 1065 MethodType initType = initMethodType(constructorType); 1066 MethodHandle initHandle = new MethodHandleImpl( 1067 constructor.getArtMethod(), MethodHandle.INVOKE_DIRECT, initType); 1068 mh = new Transformers.Construct(initHandle, constructorType); 1069 } 1070 1071 if (constructor.isVarArgs()) { 1072 mh = new Transformers.VarargsCollector(mh); 1073 } 1074 return mh; 1075 } 1076 initMethodType(MethodType constructorType)1077 private static MethodType initMethodType(MethodType constructorType) { 1078 // Returns a MethodType appropriate for class <init> 1079 // methods. Constructor MethodTypes have the form 1080 // (PT1,PT2,...)C and class <init> MethodTypes have the 1081 // form (C,PT1,PT2,...)V. 1082 assert constructorType.rtype() != void.class; 1083 1084 // Insert constructorType C as the first parameter type in 1085 // the MethodType for <init>. 1086 Class<?> [] initPtypes = new Class<?> [constructorType.ptypes().length + 1]; 1087 initPtypes[0] = constructorType.rtype(); 1088 System.arraycopy(constructorType.ptypes(), 0, initPtypes, 1, 1089 constructorType.ptypes().length); 1090 1091 // Set the return type for the <init> MethodType to be void. 1092 return MethodType.methodType(void.class, initPtypes); 1093 } 1094 1095 /** 1096 * Produces an early-bound method handle for a virtual method. 1097 * It will bypass checks for overriding methods on the receiver, 1098 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1099 * instruction from within the explicitly specified {@code specialCaller}. 1100 * The type of the method handle will be that of the method, 1101 * with a suitably restricted receiver type prepended. 1102 * (The receiver type will be {@code specialCaller} or a subtype.) 1103 * The method and all its argument types must be accessible 1104 * to the lookup object. 1105 * <p> 1106 * Before method resolution, 1107 * if the explicitly specified caller class is not identical with the 1108 * lookup class, or if this lookup object does not have 1109 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1110 * privileges, the access fails. 1111 * <p> 1112 * The returned method handle will have 1113 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1114 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1115 * <p style="font-size:smaller;"> 1116 * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, 1117 * even though the {@code invokespecial} instruction can refer to them 1118 * in special circumstances. Use {@link #findConstructor findConstructor} 1119 * to access instance initialization methods in a safe manner.)</em> 1120 * <p><b>Example:</b> 1121 * <blockquote><pre>{@code 1122 import static java.lang.invoke.MethodHandles.*; 1123 import static java.lang.invoke.MethodType.*; 1124 ... 1125 static class Listie extends ArrayList { 1126 public String toString() { return "[wee Listie]"; } 1127 static Lookup lookup() { return MethodHandles.lookup(); } 1128 } 1129 ... 1130 // no access to constructor via invokeSpecial: 1131 MethodHandle MH_newListie = Listie.lookup() 1132 .findConstructor(Listie.class, methodType(void.class)); 1133 Listie l = (Listie) MH_newListie.invokeExact(); 1134 try { assertEquals("impossible", Listie.lookup().findSpecial( 1135 Listie.class, "<init>", methodType(void.class), Listie.class)); 1136 } catch (NoSuchMethodException ex) { } // OK 1137 // access to super and self methods via invokeSpecial: 1138 MethodHandle MH_super = Listie.lookup().findSpecial( 1139 ArrayList.class, "toString" , methodType(String.class), Listie.class); 1140 MethodHandle MH_this = Listie.lookup().findSpecial( 1141 Listie.class, "toString" , methodType(String.class), Listie.class); 1142 MethodHandle MH_duper = Listie.lookup().findSpecial( 1143 Object.class, "toString" , methodType(String.class), Listie.class); 1144 assertEquals("[]", (String) MH_super.invokeExact(l)); 1145 assertEquals(""+l, (String) MH_this.invokeExact(l)); 1146 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method 1147 try { assertEquals("inaccessible", Listie.lookup().findSpecial( 1148 String.class, "toString", methodType(String.class), Listie.class)); 1149 } catch (IllegalAccessException ex) { } // OK 1150 Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; 1151 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method 1152 * }</pre></blockquote> 1153 * 1154 * @param refc the class or interface from which the method is accessed 1155 * @param name the name of the method (which must not be "<init>") 1156 * @param type the type of the method, with the receiver argument omitted 1157 * @param specialCaller the proposed calling class to perform the {@code invokespecial} 1158 * @return the desired method handle 1159 * @throws NoSuchMethodException if the method does not exist 1160 * @throws IllegalAccessException if access checking fails 1161 * or if the method's variable arity modifier bit 1162 * is set and {@code asVarargsCollector} fails 1163 * @exception SecurityException if a security manager is present and it 1164 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1165 * @throws NullPointerException if any argument is null 1166 */ findSpecial(Class<?> refc, String name, MethodType type, Class<?> specialCaller)1167 public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, 1168 Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { 1169 if (specialCaller == null) { 1170 throw new NullPointerException("specialCaller == null"); 1171 } 1172 1173 if (type == null) { 1174 throw new NullPointerException("type == null"); 1175 } 1176 1177 if (name == null) { 1178 throw new NullPointerException("name == null"); 1179 } 1180 1181 if (refc == null) { 1182 throw new NullPointerException("ref == null"); 1183 } 1184 1185 // Make sure that the special caller is identical to the lookup class or that we have 1186 // private access. 1187 // Android-changed: Also allow access to any interface methods. 1188 checkSpecialCaller(specialCaller, refc); 1189 1190 // Even though constructors are invoked using a "special" invoke, handles to them can't 1191 // be created using findSpecial. Callers must use findConstructor instead. Similarly, 1192 // there is no path for calling static class initializers. 1193 if (name.startsWith("<")) { 1194 throw new NoSuchMethodException(name + " is not a valid method name."); 1195 } 1196 1197 Method method = refc.getDeclaredMethod(name, type.ptypes()); 1198 checkReturnType(method, type); 1199 return findSpecial(method, type, refc, specialCaller); 1200 } 1201 findSpecial(Method method, MethodType type, Class<?> refc, Class<?> specialCaller)1202 private MethodHandle findSpecial(Method method, MethodType type, 1203 Class<?> refc, Class<?> specialCaller) 1204 throws IllegalAccessException { 1205 if (Modifier.isStatic(method.getModifiers())) { 1206 throw new IllegalAccessException("expected a non-static method:" + method); 1207 } 1208 1209 if (Modifier.isPrivate(method.getModifiers())) { 1210 // Since this is a private method, we'll need to also make sure that the 1211 // lookup class is the same as the refering class. We've already checked that 1212 // the specialCaller is the same as the special lookup class, both of these must 1213 // be the same as the declaring class(*) in order to access the private method. 1214 // 1215 // (*) Well, this isn't true for nested classes but OpenJDK doesn't support those 1216 // either. 1217 if (refc != lookupClass()) { 1218 throw new IllegalAccessException("no private access for invokespecial : " 1219 + refc + ", from" + this); 1220 } 1221 1222 // This is a private method, so there's nothing special to do. 1223 MethodType handleType = type.insertParameterTypes(0, refc); 1224 return createMethodHandle(method, MethodHandle.INVOKE_DIRECT, handleType); 1225 } 1226 1227 // This is a public, protected or package-private method, which means we're expecting 1228 // invoke-super semantics. We'll have to restrict the receiver type appropriately on the 1229 // handle once we check that there really is a "super" relationship between them. 1230 if (!method.getDeclaringClass().isAssignableFrom(specialCaller)) { 1231 throw new IllegalAccessException(refc + "is not assignable from " + specialCaller); 1232 } 1233 1234 // Note that we restrict the receiver to "specialCaller" instances. 1235 MethodType handleType = type.insertParameterTypes(0, specialCaller); 1236 return createMethodHandle(method, MethodHandle.INVOKE_SUPER, handleType); 1237 } 1238 1239 /** 1240 * Produces a method handle giving read access to a non-static field. 1241 * The type of the method handle will have a return type of the field's 1242 * value type. 1243 * The method handle's single argument will be the instance containing 1244 * the field. 1245 * Access checking is performed immediately on behalf of the lookup class. 1246 * @param refc the class or interface from which the method is accessed 1247 * @param name the field's name 1248 * @param type the field's type 1249 * @return a method handle which can load values from the field 1250 * @throws NoSuchFieldException if the field does not exist 1251 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1252 * @exception SecurityException if a security manager is present and it 1253 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1254 * @throws NullPointerException if any argument is null 1255 */ findGetter(Class<?> refc, String name, Class<?> type)1256 public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1257 return findAccessor(refc, name, type, MethodHandle.IGET); 1258 } 1259 findAccessor(Class<?> refc, String name, Class<?> type, int kind)1260 private MethodHandle findAccessor(Class<?> refc, String name, Class<?> type, int kind) 1261 throws NoSuchFieldException, IllegalAccessException { 1262 final Field field = findFieldOfType(refc, name, type); 1263 return findAccessor(field, refc, type, kind, true /* performAccessChecks */); 1264 } 1265 findAccessor(Field field, Class<?> refc, Class<?> type, int kind, boolean performAccessChecks)1266 private MethodHandle findAccessor(Field field, Class<?> refc, Class<?> type, int kind, 1267 boolean performAccessChecks) 1268 throws IllegalAccessException { 1269 final boolean isSetterKind = kind == MethodHandle.IPUT || kind == MethodHandle.SPUT; 1270 final boolean isStaticKind = kind == MethodHandle.SGET || kind == MethodHandle.SPUT; 1271 commonFieldChecks(field, refc, type, isStaticKind, performAccessChecks); 1272 if (performAccessChecks) { 1273 final int modifiers = field.getModifiers(); 1274 if (isSetterKind && Modifier.isFinal(modifiers)) { 1275 throw new IllegalAccessException("Field " + field + " is final"); 1276 } 1277 } 1278 1279 final MethodType methodType; 1280 switch (kind) { 1281 case MethodHandle.SGET: 1282 methodType = MethodType.methodType(type); 1283 break; 1284 case MethodHandle.SPUT: 1285 methodType = MethodType.methodType(void.class, type); 1286 break; 1287 case MethodHandle.IGET: 1288 methodType = MethodType.methodType(type, refc); 1289 break; 1290 case MethodHandle.IPUT: 1291 methodType = MethodType.methodType(void.class, refc, type); 1292 break; 1293 default: 1294 throw new IllegalArgumentException("Invalid kind " + kind); 1295 } 1296 return new MethodHandleImpl(field.getArtField(), kind, methodType); 1297 } 1298 1299 /** 1300 * Produces a method handle giving write access to a non-static field. 1301 * The type of the method handle will have a void return type. 1302 * The method handle will take two arguments, the instance containing 1303 * the field, and the value to be stored. 1304 * The second argument will be of the field's value type. 1305 * Access checking is performed immediately on behalf of the lookup class. 1306 * @param refc the class or interface from which the method is accessed 1307 * @param name the field's name 1308 * @param type the field's type 1309 * @return a method handle which can store values into the field 1310 * @throws NoSuchFieldException if the field does not exist 1311 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1312 * @exception SecurityException if a security manager is present and it 1313 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1314 * @throws NullPointerException if any argument is null 1315 */ findSetter(Class<?> refc, String name, Class<?> type)1316 public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1317 return findAccessor(refc, name, type, MethodHandle.IPUT); 1318 } 1319 1320 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method. 1321 /** 1322 * Produces a VarHandle giving access to a non-static field {@code name} 1323 * of type {@code type} declared in a class of type {@code recv}. 1324 * The VarHandle's variable type is {@code type} and it has one 1325 * coordinate type, {@code recv}. 1326 * <p> 1327 * Access checking is performed immediately on behalf of the lookup 1328 * class. 1329 * <p> 1330 * Certain access modes of the returned VarHandle are unsupported under 1331 * the following conditions: 1332 * <ul> 1333 * <li>if the field is declared {@code final}, then the write, atomic 1334 * update, numeric atomic update, and bitwise atomic update access 1335 * modes are unsupported. 1336 * <li>if the field type is anything other than {@code byte}, 1337 * {@code short}, {@code char}, {@code int}, {@code long}, 1338 * {@code float}, or {@code double} then numeric atomic update 1339 * access modes are unsupported. 1340 * <li>if the field type is anything other than {@code boolean}, 1341 * {@code byte}, {@code short}, {@code char}, {@code int} or 1342 * {@code long} then bitwise atomic update access modes are 1343 * unsupported. 1344 * </ul> 1345 * <p> 1346 * If the field is declared {@code volatile} then the returned VarHandle 1347 * will override access to the field (effectively ignore the 1348 * {@code volatile} declaration) in accordance to its specified 1349 * access modes. 1350 * <p> 1351 * If the field type is {@code float} or {@code double} then numeric 1352 * and atomic update access modes compare values using their bitwise 1353 * representation (see {@link Float#floatToRawIntBits} and 1354 * {@link Double#doubleToRawLongBits}, respectively). 1355 * @apiNote 1356 * Bitwise comparison of {@code float} values or {@code double} values, 1357 * as performed by the numeric and atomic update access modes, differ 1358 * from the primitive {@code ==} operator and the {@link Float#equals} 1359 * and {@link Double#equals} methods, specifically with respect to 1360 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1361 * Care should be taken when performing a compare and set or a compare 1362 * and exchange operation with such values since the operation may 1363 * unexpectedly fail. 1364 * There are many possible NaN values that are considered to be 1365 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1366 * provided by Java can distinguish between them. Operation failure can 1367 * occur if the expected or witness value is a NaN value and it is 1368 * transformed (perhaps in a platform specific manner) into another NaN 1369 * value, and thus has a different bitwise representation (see 1370 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1371 * details). 1372 * The values {@code -0.0} and {@code +0.0} have different bitwise 1373 * representations but are considered equal when using the primitive 1374 * {@code ==} operator. Operation failure can occur if, for example, a 1375 * numeric algorithm computes an expected value to be say {@code -0.0} 1376 * and previously computed the witness value to be say {@code +0.0}. 1377 * @param recv the receiver class, of type {@code R}, that declares the 1378 * non-static field 1379 * @param name the field's name 1380 * @param type the field's type, of type {@code T} 1381 * @return a VarHandle giving access to non-static fields. 1382 * @throws NoSuchFieldException if the field does not exist 1383 * @throws IllegalAccessException if access checking fails, or if the field is {@code static} 1384 * @exception SecurityException if a security manager is present and it 1385 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1386 * @throws NullPointerException if any argument is null 1387 * @since 9 1388 */ findVarHandle(Class<?> recv, String name, Class<?> type)1389 public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1390 final Field field = findFieldOfType(recv, name, type); 1391 final boolean isStatic = false; 1392 final boolean performAccessChecks = true; 1393 commonFieldChecks(field, recv, type, isStatic, performAccessChecks); 1394 return FieldVarHandle.create(field); 1395 } 1396 // END Android-changed: OpenJDK 9+181 VarHandle API factory method. 1397 1398 // BEGIN Android-added: Common field resolution and access check methods. findFieldOfType(final Class<?> refc, String name, Class<?> type)1399 private Field findFieldOfType(final Class<?> refc, String name, Class<?> type) 1400 throws NoSuchFieldException { 1401 Field field = null; 1402 1403 // Search refc and super classes for the field. 1404 for (Class<?> cls = refc; cls != null; cls = cls.getSuperclass()) { 1405 try { 1406 field = cls.getDeclaredField(name); 1407 break; 1408 } catch (NoSuchFieldException e) { 1409 } 1410 } 1411 1412 if (field == null) { 1413 // Force failure citing refc. 1414 field = refc.getDeclaredField(name); 1415 } 1416 1417 final Class<?> fieldType = field.getType(); 1418 if (fieldType != type) { 1419 throw new NoSuchFieldException(name); 1420 } 1421 return field; 1422 } 1423 commonFieldChecks(Field field, Class<?> refc, Class<?> type, boolean isStatic, boolean performAccessChecks)1424 private void commonFieldChecks(Field field, Class<?> refc, Class<?> type, 1425 boolean isStatic, boolean performAccessChecks) 1426 throws IllegalAccessException { 1427 final int modifiers = field.getModifiers(); 1428 if (performAccessChecks) { 1429 checkAccess(refc, field.getDeclaringClass(), modifiers, field.getName()); 1430 } 1431 if (Modifier.isStatic(modifiers) != isStatic) { 1432 String reason = "Field " + field + " is " + 1433 (isStatic ? "not " : "") + "static"; 1434 throw new IllegalAccessException(reason); 1435 } 1436 } 1437 // END Android-added: Common field resolution and access check methods. 1438 1439 /** 1440 * Produces a method handle giving read access to a static field. 1441 * The type of the method handle will have a return type of the field's 1442 * value type. 1443 * The method handle will take no arguments. 1444 * Access checking is performed immediately on behalf of the lookup class. 1445 * <p> 1446 * If the returned method handle is invoked, the field's class will 1447 * be initialized, if it has not already been initialized. 1448 * @param refc the class or interface from which the method is accessed 1449 * @param name the field's name 1450 * @param type the field's type 1451 * @return a method handle which can load values from the field 1452 * @throws NoSuchFieldException if the field does not exist 1453 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1454 * @exception SecurityException if a security manager is present and it 1455 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1456 * @throws NullPointerException if any argument is null 1457 */ findStaticGetter(Class<?> refc, String name, Class<?> type)1458 public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1459 return findAccessor(refc, name, type, MethodHandle.SGET); 1460 } 1461 1462 /** 1463 * Produces a method handle giving write access to a static field. 1464 * The type of the method handle will have a void return type. 1465 * The method handle will take a single 1466 * argument, of the field's value type, the value to be stored. 1467 * Access checking is performed immediately on behalf of the lookup class. 1468 * <p> 1469 * If the returned method handle is invoked, the field's class will 1470 * be initialized, if it has not already been initialized. 1471 * @param refc the class or interface from which the method is accessed 1472 * @param name the field's name 1473 * @param type the field's type 1474 * @return a method handle which can store values into the field 1475 * @throws NoSuchFieldException if the field does not exist 1476 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1477 * @exception SecurityException if a security manager is present and it 1478 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1479 * @throws NullPointerException if any argument is null 1480 */ findStaticSetter(Class<?> refc, String name, Class<?> type)1481 public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1482 return findAccessor(refc, name, type, MethodHandle.SPUT); 1483 } 1484 1485 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method. 1486 /** 1487 * Produces a VarHandle giving access to a static field {@code name} of 1488 * type {@code type} declared in a class of type {@code decl}. 1489 * The VarHandle's variable type is {@code type} and it has no 1490 * coordinate types. 1491 * <p> 1492 * Access checking is performed immediately on behalf of the lookup 1493 * class. 1494 * <p> 1495 * If the returned VarHandle is operated on, the declaring class will be 1496 * initialized, if it has not already been initialized. 1497 * <p> 1498 * Certain access modes of the returned VarHandle are unsupported under 1499 * the following conditions: 1500 * <ul> 1501 * <li>if the field is declared {@code final}, then the write, atomic 1502 * update, numeric atomic update, and bitwise atomic update access 1503 * modes are unsupported. 1504 * <li>if the field type is anything other than {@code byte}, 1505 * {@code short}, {@code char}, {@code int}, {@code long}, 1506 * {@code float}, or {@code double}, then numeric atomic update 1507 * access modes are unsupported. 1508 * <li>if the field type is anything other than {@code boolean}, 1509 * {@code byte}, {@code short}, {@code char}, {@code int} or 1510 * {@code long} then bitwise atomic update access modes are 1511 * unsupported. 1512 * </ul> 1513 * <p> 1514 * If the field is declared {@code volatile} then the returned VarHandle 1515 * will override access to the field (effectively ignore the 1516 * {@code volatile} declaration) in accordance to its specified 1517 * access modes. 1518 * <p> 1519 * If the field type is {@code float} or {@code double} then numeric 1520 * and atomic update access modes compare values using their bitwise 1521 * representation (see {@link Float#floatToRawIntBits} and 1522 * {@link Double#doubleToRawLongBits}, respectively). 1523 * @apiNote 1524 * Bitwise comparison of {@code float} values or {@code double} values, 1525 * as performed by the numeric and atomic update access modes, differ 1526 * from the primitive {@code ==} operator and the {@link Float#equals} 1527 * and {@link Double#equals} methods, specifically with respect to 1528 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1529 * Care should be taken when performing a compare and set or a compare 1530 * and exchange operation with such values since the operation may 1531 * unexpectedly fail. 1532 * There are many possible NaN values that are considered to be 1533 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1534 * provided by Java can distinguish between them. Operation failure can 1535 * occur if the expected or witness value is a NaN value and it is 1536 * transformed (perhaps in a platform specific manner) into another NaN 1537 * value, and thus has a different bitwise representation (see 1538 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1539 * details). 1540 * The values {@code -0.0} and {@code +0.0} have different bitwise 1541 * representations but are considered equal when using the primitive 1542 * {@code ==} operator. Operation failure can occur if, for example, a 1543 * numeric algorithm computes an expected value to be say {@code -0.0} 1544 * and previously computed the witness value to be say {@code +0.0}. 1545 * @param decl the class that declares the static field 1546 * @param name the field's name 1547 * @param type the field's type, of type {@code T} 1548 * @return a VarHandle giving access to a static field 1549 * @throws NoSuchFieldException if the field does not exist 1550 * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} 1551 * @exception SecurityException if a security manager is present and it 1552 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1553 * @throws NullPointerException if any argument is null 1554 * @since 9 1555 */ findStaticVarHandle(Class<?> decl, String name, Class<?> type)1556 public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { 1557 final Field field = findFieldOfType(decl, name, type); 1558 final boolean isStatic = true; 1559 final boolean performAccessChecks = true; 1560 commonFieldChecks(field, decl, type, isStatic, performAccessChecks); 1561 return StaticFieldVarHandle.create(field); 1562 } 1563 // END Android-changed: OpenJDK 9+181 VarHandle API factory method. 1564 1565 /** 1566 * Produces an early-bound method handle for a non-static method. 1567 * The receiver must have a supertype {@code defc} in which a method 1568 * of the given name and type is accessible to the lookup class. 1569 * The method and all its argument types must be accessible to the lookup object. 1570 * The type of the method handle will be that of the method, 1571 * without any insertion of an additional receiver parameter. 1572 * The given receiver will be bound into the method handle, 1573 * so that every call to the method handle will invoke the 1574 * requested method on the given receiver. 1575 * <p> 1576 * The returned method handle will have 1577 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1578 * the method's variable arity modifier bit ({@code 0x0080}) is set 1579 * <em>and</em> the trailing array argument is not the only argument. 1580 * (If the trailing array argument is the only argument, 1581 * the given receiver value will be bound to it.) 1582 * <p> 1583 * This is equivalent to the following code: 1584 * <blockquote><pre>{@code 1585 import static java.lang.invoke.MethodHandles.*; 1586 import static java.lang.invoke.MethodType.*; 1587 ... 1588 MethodHandle mh0 = lookup().findVirtual(defc, name, type); 1589 MethodHandle mh1 = mh0.bindTo(receiver); 1590 MethodType mt1 = mh1.type(); 1591 if (mh0.isVarargsCollector()) 1592 mh1 = mh1.asVarargsCollector(mt1.parameterType(mt1.parameterCount()-1)); 1593 return mh1; 1594 * }</pre></blockquote> 1595 * where {@code defc} is either {@code receiver.getClass()} or a super 1596 * type of that class, in which the requested method is accessible 1597 * to the lookup class. 1598 * (Note that {@code bindTo} does not preserve variable arity.) 1599 * @param receiver the object from which the method is accessed 1600 * @param name the name of the method 1601 * @param type the type of the method, with the receiver argument omitted 1602 * @return the desired method handle 1603 * @throws NoSuchMethodException if the method does not exist 1604 * @throws IllegalAccessException if access checking fails 1605 * or if the method's variable arity modifier bit 1606 * is set and {@code asVarargsCollector} fails 1607 * @exception SecurityException if a security manager is present and it 1608 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1609 * @throws NullPointerException if any argument is null 1610 * @see MethodHandle#bindTo 1611 * @see #findVirtual 1612 */ bind(Object receiver, String name, MethodType type)1613 public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { 1614 MethodHandle handle = findVirtual(receiver.getClass(), name, type); 1615 MethodHandle adapter = handle.bindTo(receiver); 1616 MethodType adapterType = adapter.type(); 1617 if (handle.isVarargsCollector()) { 1618 adapter = adapter.asVarargsCollector( 1619 adapterType.parameterType(adapterType.parameterCount() - 1)); 1620 } 1621 1622 return adapter; 1623 } 1624 1625 /** 1626 * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1627 * to <i>m</i>, if the lookup class has permission. 1628 * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. 1629 * If <i>m</i> is virtual, overriding is respected on every call. 1630 * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. 1631 * The type of the method handle will be that of the method, 1632 * with the receiver type prepended (but only if it is non-static). 1633 * If the method's {@code accessible} flag is not set, 1634 * access checking is performed immediately on behalf of the lookup class. 1635 * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. 1636 * <p> 1637 * The returned method handle will have 1638 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1639 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1640 * <p> 1641 * If <i>m</i> is static, and 1642 * if the returned method handle is invoked, the method's class will 1643 * be initialized, if it has not already been initialized. 1644 * @param m the reflected method 1645 * @return a method handle which can invoke the reflected method 1646 * @throws IllegalAccessException if access checking fails 1647 * or if the method's variable arity modifier bit 1648 * is set and {@code asVarargsCollector} fails 1649 * @throws NullPointerException if the argument is null 1650 */ unreflect(Method m)1651 public MethodHandle unreflect(Method m) throws IllegalAccessException { 1652 if (m == null) { 1653 throw new NullPointerException("m == null"); 1654 } 1655 1656 MethodType methodType = MethodType.methodType(m.getReturnType(), 1657 m.getParameterTypes()); 1658 1659 // We should only perform access checks if setAccessible hasn't been called yet. 1660 if (!m.isAccessible()) { 1661 checkAccess(m.getDeclaringClass(), m.getDeclaringClass(), m.getModifiers(), 1662 m.getName()); 1663 } 1664 1665 if (Modifier.isStatic(m.getModifiers())) { 1666 return createMethodHandle(m, MethodHandle.INVOKE_STATIC, methodType); 1667 } else { 1668 methodType = methodType.insertParameterTypes(0, m.getDeclaringClass()); 1669 return createMethodHandle(m, MethodHandle.INVOKE_VIRTUAL, methodType); 1670 } 1671 } 1672 1673 /** 1674 * Produces a method handle for a reflected method. 1675 * It will bypass checks for overriding methods on the receiver, 1676 * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} 1677 * instruction from within the explicitly specified {@code specialCaller}. 1678 * The type of the method handle will be that of the method, 1679 * with a suitably restricted receiver type prepended. 1680 * (The receiver type will be {@code specialCaller} or a subtype.) 1681 * If the method's {@code accessible} flag is not set, 1682 * access checking is performed immediately on behalf of the lookup class, 1683 * as if {@code invokespecial} instruction were being linked. 1684 * <p> 1685 * Before method resolution, 1686 * if the explicitly specified caller class is not identical with the 1687 * lookup class, or if this lookup object does not have 1688 * <a href="MethodHandles.Lookup.html#privacc">private access</a> 1689 * privileges, the access fails. 1690 * <p> 1691 * The returned method handle will have 1692 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1693 * the method's variable arity modifier bit ({@code 0x0080}) is set. 1694 * @param m the reflected method 1695 * @param specialCaller the class nominally calling the method 1696 * @return a method handle which can invoke the reflected method 1697 * @throws IllegalAccessException if access checking fails 1698 * or if the method's variable arity modifier bit 1699 * is set and {@code asVarargsCollector} fails 1700 * @throws NullPointerException if any argument is null 1701 */ unreflectSpecial(Method m, Class<?> specialCaller)1702 public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { 1703 if (m == null) { 1704 throw new NullPointerException("m == null"); 1705 } 1706 1707 if (specialCaller == null) { 1708 throw new NullPointerException("specialCaller == null"); 1709 } 1710 1711 if (!m.isAccessible()) { 1712 // Android-changed: Match Java language 9 behavior where unreflectSpecial continues 1713 // to require exact caller lookupClass match. 1714 checkSpecialCaller(specialCaller, null); 1715 } 1716 1717 final MethodType methodType = MethodType.methodType(m.getReturnType(), 1718 m.getParameterTypes()); 1719 return findSpecial(m, methodType, m.getDeclaringClass() /* refc */, specialCaller); 1720 } 1721 1722 /** 1723 * Produces a method handle for a reflected constructor. 1724 * The type of the method handle will be that of the constructor, 1725 * with the return type changed to the declaring class. 1726 * The method handle will perform a {@code newInstance} operation, 1727 * creating a new instance of the constructor's class on the 1728 * arguments passed to the method handle. 1729 * <p> 1730 * If the constructor's {@code accessible} flag is not set, 1731 * access checking is performed immediately on behalf of the lookup class. 1732 * <p> 1733 * The returned method handle will have 1734 * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if 1735 * the constructor's variable arity modifier bit ({@code 0x0080}) is set. 1736 * <p> 1737 * If the returned method handle is invoked, the constructor's class will 1738 * be initialized, if it has not already been initialized. 1739 * @param c the reflected constructor 1740 * @return a method handle which can invoke the reflected constructor 1741 * @throws IllegalAccessException if access checking fails 1742 * or if the method's variable arity modifier bit 1743 * is set and {@code asVarargsCollector} fails 1744 * @throws NullPointerException if the argument is null 1745 */ unreflectConstructor(Constructor<?> c)1746 public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { 1747 if (c == null) { 1748 throw new NullPointerException("c == null"); 1749 } 1750 1751 if (!c.isAccessible()) { 1752 checkAccess(c.getDeclaringClass(), c.getDeclaringClass(), c.getModifiers(), 1753 c.getName()); 1754 } 1755 1756 return createMethodHandleForConstructor(c); 1757 } 1758 1759 /** 1760 * Produces a method handle giving read access to a reflected field. 1761 * The type of the method handle will have a return type of the field's 1762 * value type. 1763 * If the field is static, the method handle will take no arguments. 1764 * Otherwise, its single argument will be the instance containing 1765 * the field. 1766 * If the field's {@code accessible} flag is not set, 1767 * access checking is performed immediately on behalf of the lookup class. 1768 * <p> 1769 * If the field is static, and 1770 * if the returned method handle is invoked, the field's class will 1771 * be initialized, if it has not already been initialized. 1772 * @param f the reflected field 1773 * @return a method handle which can load values from the reflected field 1774 * @throws IllegalAccessException if access checking fails 1775 * @throws NullPointerException if the argument is null 1776 */ unreflectGetter(Field f)1777 public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { 1778 return findAccessor(f, f.getDeclaringClass(), f.getType(), 1779 Modifier.isStatic(f.getModifiers()) ? MethodHandle.SGET : MethodHandle.IGET, 1780 !f.isAccessible() /* performAccessChecks */); 1781 } 1782 1783 /** 1784 * Produces a method handle giving write access to a reflected field. 1785 * The type of the method handle will have a void return type. 1786 * If the field is static, the method handle will take a single 1787 * argument, of the field's value type, the value to be stored. 1788 * Otherwise, the two arguments will be the instance containing 1789 * the field, and the value to be stored. 1790 * If the field's {@code accessible} flag is not set, 1791 * access checking is performed immediately on behalf of the lookup class. 1792 * <p> 1793 * If the field is static, and 1794 * if the returned method handle is invoked, the field's class will 1795 * be initialized, if it has not already been initialized. 1796 * @param f the reflected field 1797 * @return a method handle which can store values into the reflected field 1798 * @throws IllegalAccessException if access checking fails 1799 * @throws NullPointerException if the argument is null 1800 */ unreflectSetter(Field f)1801 public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { 1802 return findAccessor(f, f.getDeclaringClass(), f.getType(), 1803 Modifier.isStatic(f.getModifiers()) ? MethodHandle.SPUT : MethodHandle.IPUT, 1804 !f.isAccessible() /* performAccessChecks */); 1805 } 1806 1807 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory method. 1808 /** 1809 * Produces a VarHandle giving access to a reflected field {@code f} 1810 * of type {@code T} declared in a class of type {@code R}. 1811 * The VarHandle's variable type is {@code T}. 1812 * If the field is non-static the VarHandle has one coordinate type, 1813 * {@code R}. Otherwise, the field is static, and the VarHandle has no 1814 * coordinate types. 1815 * <p> 1816 * Access checking is performed immediately on behalf of the lookup 1817 * class, regardless of the value of the field's {@code accessible} 1818 * flag. 1819 * <p> 1820 * If the field is static, and if the returned VarHandle is operated 1821 * on, the field's declaring class will be initialized, if it has not 1822 * already been initialized. 1823 * <p> 1824 * Certain access modes of the returned VarHandle are unsupported under 1825 * the following conditions: 1826 * <ul> 1827 * <li>if the field is declared {@code final}, then the write, atomic 1828 * update, numeric atomic update, and bitwise atomic update access 1829 * modes are unsupported. 1830 * <li>if the field type is anything other than {@code byte}, 1831 * {@code short}, {@code char}, {@code int}, {@code long}, 1832 * {@code float}, or {@code double} then numeric atomic update 1833 * access modes are unsupported. 1834 * <li>if the field type is anything other than {@code boolean}, 1835 * {@code byte}, {@code short}, {@code char}, {@code int} or 1836 * {@code long} then bitwise atomic update access modes are 1837 * unsupported. 1838 * </ul> 1839 * <p> 1840 * If the field is declared {@code volatile} then the returned VarHandle 1841 * will override access to the field (effectively ignore the 1842 * {@code volatile} declaration) in accordance to its specified 1843 * access modes. 1844 * <p> 1845 * If the field type is {@code float} or {@code double} then numeric 1846 * and atomic update access modes compare values using their bitwise 1847 * representation (see {@link Float#floatToRawIntBits} and 1848 * {@link Double#doubleToRawLongBits}, respectively). 1849 * @apiNote 1850 * Bitwise comparison of {@code float} values or {@code double} values, 1851 * as performed by the numeric and atomic update access modes, differ 1852 * from the primitive {@code ==} operator and the {@link Float#equals} 1853 * and {@link Double#equals} methods, specifically with respect to 1854 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 1855 * Care should be taken when performing a compare and set or a compare 1856 * and exchange operation with such values since the operation may 1857 * unexpectedly fail. 1858 * There are many possible NaN values that are considered to be 1859 * {@code NaN} in Java, although no IEEE 754 floating-point operation 1860 * provided by Java can distinguish between them. Operation failure can 1861 * occur if the expected or witness value is a NaN value and it is 1862 * transformed (perhaps in a platform specific manner) into another NaN 1863 * value, and thus has a different bitwise representation (see 1864 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 1865 * details). 1866 * The values {@code -0.0} and {@code +0.0} have different bitwise 1867 * representations but are considered equal when using the primitive 1868 * {@code ==} operator. Operation failure can occur if, for example, a 1869 * numeric algorithm computes an expected value to be say {@code -0.0} 1870 * and previously computed the witness value to be say {@code +0.0}. 1871 * @param f the reflected field, with a field of type {@code T}, and 1872 * a declaring class of type {@code R} 1873 * @return a VarHandle giving access to non-static fields or a static 1874 * field 1875 * @throws IllegalAccessException if access checking fails 1876 * @throws NullPointerException if the argument is null 1877 * @since 9 1878 */ unreflectVarHandle(Field f)1879 public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { 1880 final boolean isStatic = Modifier.isStatic(f.getModifiers()); 1881 final boolean performAccessChecks = true; 1882 commonFieldChecks(f, f.getDeclaringClass(), f.getType(), isStatic, performAccessChecks); 1883 return isStatic ? StaticFieldVarHandle.create(f) : FieldVarHandle.create(f); 1884 } 1885 // END Android-changed: OpenJDK 9+181 VarHandle API factory method. 1886 1887 /** 1888 * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> 1889 * created by this lookup object or a similar one. 1890 * Security and access checks are performed to ensure that this lookup object 1891 * is capable of reproducing the target method handle. 1892 * This means that the cracking may fail if target is a direct method handle 1893 * but was created by an unrelated lookup object. 1894 * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> 1895 * and was created by a lookup object for a different class. 1896 * @param target a direct method handle to crack into symbolic reference components 1897 * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object 1898 * @exception SecurityException if a security manager is present and it 1899 * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> 1900 * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails 1901 * @exception NullPointerException if the target is {@code null} 1902 * @see MethodHandleInfo 1903 * @since 1.8 1904 */ revealDirect(MethodHandle target)1905 public MethodHandleInfo revealDirect(MethodHandle target) { 1906 MethodHandleImpl directTarget = getMethodHandleImpl(target); 1907 MethodHandleInfo info = directTarget.reveal(); 1908 1909 try { 1910 checkAccess(lookupClass(), info.getDeclaringClass(), info.getModifiers(), 1911 info.getName()); 1912 } catch (IllegalAccessException exception) { 1913 throw new IllegalArgumentException("Unable to access memeber.", exception); 1914 } 1915 1916 return info; 1917 } 1918 hasPrivateAccess()1919 private boolean hasPrivateAccess() { 1920 return (allowedModes & PRIVATE) != 0; 1921 } 1922 1923 /** Check public/protected/private bits on the symbolic reference class and its member. */ checkAccess(Class<?> refc, Class<?> defc, int mods, String methName)1924 void checkAccess(Class<?> refc, Class<?> defc, int mods, String methName) 1925 throws IllegalAccessException { 1926 int allowedModes = this.allowedModes; 1927 1928 if (Modifier.isProtected(mods) && 1929 defc == Object.class && 1930 "clone".equals(methName) && 1931 refc.isArray()) { 1932 // The JVM does this hack also. 1933 // (See ClassVerifier::verify_invoke_instructions 1934 // and LinkResolver::check_method_accessability.) 1935 // Because the JVM does not allow separate methods on array types, 1936 // there is no separate method for int[].clone. 1937 // All arrays simply inherit Object.clone. 1938 // But for access checking logic, we make Object.clone 1939 // (normally protected) appear to be public. 1940 // Later on, when the DirectMethodHandle is created, 1941 // its leading argument will be restricted to the 1942 // requested array type. 1943 // N.B. The return type is not adjusted, because 1944 // that is *not* the bytecode behavior. 1945 mods ^= Modifier.PROTECTED | Modifier.PUBLIC; 1946 } 1947 1948 if (Modifier.isProtected(mods) && Modifier.isConstructor(mods)) { 1949 // cannot "new" a protected ctor in a different package 1950 mods ^= Modifier.PROTECTED; 1951 } 1952 1953 if (Modifier.isPublic(mods) && Modifier.isPublic(refc.getModifiers()) && allowedModes != 0) 1954 return; // common case 1955 int requestedModes = fixmods(mods); // adjust 0 => PACKAGE 1956 if ((requestedModes & allowedModes) != 0) { 1957 if (VerifyAccess.isMemberAccessible(refc, defc, mods, lookupClass(), allowedModes)) 1958 return; 1959 } else { 1960 // Protected members can also be checked as if they were package-private. 1961 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 1962 && VerifyAccess.isSamePackage(defc, lookupClass())) 1963 return; 1964 } 1965 1966 throwMakeAccessException(accessFailedMessage(refc, defc, mods), this); 1967 } 1968 accessFailedMessage(Class<?> refc, Class<?> defc, int mods)1969 String accessFailedMessage(Class<?> refc, Class<?> defc, int mods) { 1970 // check the class first: 1971 boolean classOK = (Modifier.isPublic(defc.getModifiers()) && 1972 (defc == refc || 1973 Modifier.isPublic(refc.getModifiers()))); 1974 if (!classOK && (allowedModes & PACKAGE) != 0) { 1975 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && 1976 (defc == refc || 1977 VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); 1978 } 1979 if (!classOK) 1980 return "class is not public"; 1981 if (Modifier.isPublic(mods)) 1982 return "access to public member failed"; // (how?) 1983 if (Modifier.isPrivate(mods)) 1984 return "member is private"; 1985 if (Modifier.isProtected(mods)) 1986 return "member is protected"; 1987 return "member is private to package"; 1988 } 1989 1990 // Android-changed: checkSpecialCaller assumes that ALLOW_NESTMATE_ACCESS = false, 1991 // as in upstream OpenJDK. 1992 // 1993 // private static final boolean ALLOW_NESTMATE_ACCESS = false; 1994 1995 // Android-changed: Match java language 9 behavior allowing special access if the reflected 1996 // class (called 'refc', the class from which the method is being accessed) is an interface 1997 // and is implemented by the caller. checkSpecialCaller(Class<?> specialCaller, Class<?> refc)1998 private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { 1999 // Android-changed: No support for TRUSTED lookups. Also construct the 2000 // IllegalAccessException by hand because the upstream code implicitly assumes 2001 // that the lookupClass == specialCaller. 2002 // 2003 // if (allowedModes == TRUSTED) return; 2004 boolean isInterfaceLookup = (refc != null && 2005 refc.isInterface() && 2006 refc.isAssignableFrom(specialCaller)); 2007 if (!hasPrivateAccess() || (specialCaller != lookupClass() && !isInterfaceLookup)) { 2008 throw new IllegalAccessException("no private access for invokespecial : " 2009 + specialCaller + ", from" + this); 2010 } 2011 } 2012 throwMakeAccessException(String message, Object from)2013 private void throwMakeAccessException(String message, Object from) throws 2014 IllegalAccessException{ 2015 message = message + ": "+ toString(); 2016 if (from != null) message += ", from " + from; 2017 throw new IllegalAccessException(message); 2018 } 2019 checkReturnType(Method method, MethodType methodType)2020 private void checkReturnType(Method method, MethodType methodType) 2021 throws NoSuchMethodException { 2022 if (method.getReturnType() != methodType.rtype()) { 2023 throw new NoSuchMethodException(method.getName() + methodType); 2024 } 2025 } 2026 } 2027 2028 /** 2029 * "Cracks" {@code target} to reveal the underlying {@code MethodHandleImpl}. 2030 */ getMethodHandleImpl(MethodHandle target)2031 private static MethodHandleImpl getMethodHandleImpl(MethodHandle target) { 2032 // Special case : We implement handles to constructors as transformers, 2033 // so we must extract the underlying handle from the transformer. 2034 if (target instanceof Transformers.Construct) { 2035 target = ((Transformers.Construct) target).getConstructorHandle(); 2036 } 2037 2038 // Special case: Var-args methods are also implemented as Transformers, 2039 // so we should get the underlying handle in that case as well. 2040 if (target instanceof Transformers.VarargsCollector) { 2041 target = target.asFixedArity(); 2042 } 2043 2044 if (target instanceof MethodHandleImpl) { 2045 return (MethodHandleImpl) target; 2046 } 2047 2048 throw new IllegalArgumentException(target + " is not a direct handle"); 2049 } 2050 2051 // Android-removed: unsupported @jvms tag in doc-comment. 2052 /** 2053 * Produces a method handle constructing arrays of a desired type, 2054 * as if by the {@code anewarray} bytecode. 2055 * The return type of the method handle will be the array type. 2056 * The type of its sole argument will be {@code int}, which specifies the size of the array. 2057 * 2058 * <p> If the returned method handle is invoked with a negative 2059 * array size, a {@code NegativeArraySizeException} will be thrown. 2060 * 2061 * @param arrayClass an array type 2062 * @return a method handle which can create arrays of the given type 2063 * @throws NullPointerException if the argument is {@code null} 2064 * @throws IllegalArgumentException if {@code arrayClass} is not an array type 2065 * @see java.lang.reflect.Array#newInstance(Class, int) 2066 * @since 9 2067 */ 2068 public static arrayConstructor(Class<?> arrayClass)2069 MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { 2070 if (!arrayClass.isArray()) { 2071 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2072 } 2073 // Android-changed: transformer based implementation. 2074 // MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). 2075 // bindTo(arrayClass.getComponentType()); 2076 // return ani.asType(ani.type().changeReturnType(arrayClass)) 2077 return new Transformers.ArrayConstructor(arrayClass); 2078 } 2079 2080 // Android-removed: unsupported @jvms tag in doc-comment. 2081 /** 2082 * Produces a method handle returning the length of an array, 2083 * as if by the {@code arraylength} bytecode. 2084 * The type of the method handle will have {@code int} as return type, 2085 * and its sole argument will be the array type. 2086 * 2087 * <p> If the returned method handle is invoked with a {@code null} 2088 * array reference, a {@code NullPointerException} will be thrown. 2089 * 2090 * @param arrayClass an array type 2091 * @return a method handle which can retrieve the length of an array of the given array type 2092 * @throws NullPointerException if the argument is {@code null} 2093 * @throws IllegalArgumentException if arrayClass is not an array type 2094 * @since 9 2095 */ 2096 public static arrayLength(Class<?> arrayClass)2097 MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { 2098 // Android-changed: transformer based implementation. 2099 // return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); 2100 if (!arrayClass.isArray()) { 2101 throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); 2102 } 2103 return new Transformers.ArrayLength(arrayClass); 2104 } 2105 2106 // BEGIN Android-added: method to check if a class is an array. checkClassIsArray(Class<?> c)2107 private static void checkClassIsArray(Class<?> c) { 2108 if (!c.isArray()) { 2109 throw new IllegalArgumentException("Not an array type: " + c); 2110 } 2111 } 2112 checkTypeIsViewable(Class<?> componentType)2113 private static void checkTypeIsViewable(Class<?> componentType) { 2114 if (componentType == short.class || 2115 componentType == char.class || 2116 componentType == int.class || 2117 componentType == long.class || 2118 componentType == float.class || 2119 componentType == double.class) { 2120 return; 2121 } 2122 throw new UnsupportedOperationException("Component type not supported: " + componentType); 2123 } 2124 // END Android-added: method to check if a class is an array. 2125 2126 /** 2127 * Produces a method handle giving read access to elements of an array. 2128 * The type of the method handle will have a return type of the array's 2129 * element type. Its first argument will be the array type, 2130 * and the second will be {@code int}. 2131 * @param arrayClass an array type 2132 * @return a method handle which can load values from the given array type 2133 * @throws NullPointerException if the argument is null 2134 * @throws IllegalArgumentException if arrayClass is not an array type 2135 */ 2136 public static arrayElementGetter(Class<?> arrayClass)2137 MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { 2138 checkClassIsArray(arrayClass); 2139 final Class<?> componentType = arrayClass.getComponentType(); 2140 if (componentType.isPrimitive()) { 2141 try { 2142 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class, 2143 "arrayElementGetter", 2144 MethodType.methodType(componentType, arrayClass, int.class)); 2145 } catch (NoSuchMethodException | IllegalAccessException exception) { 2146 throw new AssertionError(exception); 2147 } 2148 } 2149 2150 return new Transformers.ReferenceArrayElementGetter(arrayClass); 2151 } 2152 arrayElementGetter(byte[] array, int i)2153 /** @hide */ public static byte arrayElementGetter(byte[] array, int i) { return array[i]; } arrayElementGetter(boolean[] array, int i)2154 /** @hide */ public static boolean arrayElementGetter(boolean[] array, int i) { return array[i]; } arrayElementGetter(char[] array, int i)2155 /** @hide */ public static char arrayElementGetter(char[] array, int i) { return array[i]; } arrayElementGetter(short[] array, int i)2156 /** @hide */ public static short arrayElementGetter(short[] array, int i) { return array[i]; } arrayElementGetter(int[] array, int i)2157 /** @hide */ public static int arrayElementGetter(int[] array, int i) { return array[i]; } arrayElementGetter(long[] array, int i)2158 /** @hide */ public static long arrayElementGetter(long[] array, int i) { return array[i]; } arrayElementGetter(float[] array, int i)2159 /** @hide */ public static float arrayElementGetter(float[] array, int i) { return array[i]; } arrayElementGetter(double[] array, int i)2160 /** @hide */ public static double arrayElementGetter(double[] array, int i) { return array[i]; } 2161 2162 /** 2163 * Produces a method handle giving write access to elements of an array. 2164 * The type of the method handle will have a void return type. 2165 * Its last argument will be the array's element type. 2166 * The first and second arguments will be the array type and int. 2167 * @param arrayClass the class of an array 2168 * @return a method handle which can store values into the array type 2169 * @throws NullPointerException if the argument is null 2170 * @throws IllegalArgumentException if arrayClass is not an array type 2171 */ 2172 public static arrayElementSetter(Class<?> arrayClass)2173 MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { 2174 checkClassIsArray(arrayClass); 2175 final Class<?> componentType = arrayClass.getComponentType(); 2176 if (componentType.isPrimitive()) { 2177 try { 2178 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class, 2179 "arrayElementSetter", 2180 MethodType.methodType(void.class, arrayClass, int.class, componentType)); 2181 } catch (NoSuchMethodException | IllegalAccessException exception) { 2182 throw new AssertionError(exception); 2183 } 2184 } 2185 2186 return new Transformers.ReferenceArrayElementSetter(arrayClass); 2187 } 2188 2189 /** @hide */ arrayElementSetter(byte[] array, int i, byte val)2190 public static void arrayElementSetter(byte[] array, int i, byte val) { array[i] = val; } 2191 /** @hide */ arrayElementSetter(boolean[] array, int i, boolean val)2192 public static void arrayElementSetter(boolean[] array, int i, boolean val) { array[i] = val; } 2193 /** @hide */ arrayElementSetter(char[] array, int i, char val)2194 public static void arrayElementSetter(char[] array, int i, char val) { array[i] = val; } 2195 /** @hide */ arrayElementSetter(short[] array, int i, short val)2196 public static void arrayElementSetter(short[] array, int i, short val) { array[i] = val; } 2197 /** @hide */ arrayElementSetter(int[] array, int i, int val)2198 public static void arrayElementSetter(int[] array, int i, int val) { array[i] = val; } 2199 /** @hide */ arrayElementSetter(long[] array, int i, long val)2200 public static void arrayElementSetter(long[] array, int i, long val) { array[i] = val; } 2201 /** @hide */ arrayElementSetter(float[] array, int i, float val)2202 public static void arrayElementSetter(float[] array, int i, float val) { array[i] = val; } 2203 /** @hide */ arrayElementSetter(double[] array, int i, double val)2204 public static void arrayElementSetter(double[] array, int i, double val) { array[i] = val; } 2205 2206 // BEGIN Android-changed: OpenJDK 9+181 VarHandle API factory methods. 2207 /** 2208 * Produces a VarHandle giving access to elements of an array of type 2209 * {@code arrayClass}. The VarHandle's variable type is the component type 2210 * of {@code arrayClass} and the list of coordinate types is 2211 * {@code (arrayClass, int)}, where the {@code int} coordinate type 2212 * corresponds to an argument that is an index into an array. 2213 * <p> 2214 * Certain access modes of the returned VarHandle are unsupported under 2215 * the following conditions: 2216 * <ul> 2217 * <li>if the component type is anything other than {@code byte}, 2218 * {@code short}, {@code char}, {@code int}, {@code long}, 2219 * {@code float}, or {@code double} then numeric atomic update access 2220 * modes are unsupported. 2221 * <li>if the field type is anything other than {@code boolean}, 2222 * {@code byte}, {@code short}, {@code char}, {@code int} or 2223 * {@code long} then bitwise atomic update access modes are 2224 * unsupported. 2225 * </ul> 2226 * <p> 2227 * If the component type is {@code float} or {@code double} then numeric 2228 * and atomic update access modes compare values using their bitwise 2229 * representation (see {@link Float#floatToRawIntBits} and 2230 * {@link Double#doubleToRawLongBits}, respectively). 2231 * @apiNote 2232 * Bitwise comparison of {@code float} values or {@code double} values, 2233 * as performed by the numeric and atomic update access modes, differ 2234 * from the primitive {@code ==} operator and the {@link Float#equals} 2235 * and {@link Double#equals} methods, specifically with respect to 2236 * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. 2237 * Care should be taken when performing a compare and set or a compare 2238 * and exchange operation with such values since the operation may 2239 * unexpectedly fail. 2240 * There are many possible NaN values that are considered to be 2241 * {@code NaN} in Java, although no IEEE 754 floating-point operation 2242 * provided by Java can distinguish between them. Operation failure can 2243 * occur if the expected or witness value is a NaN value and it is 2244 * transformed (perhaps in a platform specific manner) into another NaN 2245 * value, and thus has a different bitwise representation (see 2246 * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more 2247 * details). 2248 * The values {@code -0.0} and {@code +0.0} have different bitwise 2249 * representations but are considered equal when using the primitive 2250 * {@code ==} operator. Operation failure can occur if, for example, a 2251 * numeric algorithm computes an expected value to be say {@code -0.0} 2252 * and previously computed the witness value to be say {@code +0.0}. 2253 * @param arrayClass the class of an array, of type {@code T[]} 2254 * @return a VarHandle giving access to elements of an array 2255 * @throws NullPointerException if the arrayClass is null 2256 * @throws IllegalArgumentException if arrayClass is not an array type 2257 * @since 9 2258 */ 2259 public static arrayElementVarHandle(Class<?> arrayClass)2260 VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { 2261 checkClassIsArray(arrayClass); 2262 return ArrayElementVarHandle.create(arrayClass); 2263 } 2264 2265 /** 2266 * Produces a VarHandle giving access to elements of a {@code byte[]} array 2267 * viewed as if it were a different primitive array type, such as 2268 * {@code int[]} or {@code long[]}. 2269 * The VarHandle's variable type is the component type of 2270 * {@code viewArrayClass} and the list of coordinate types is 2271 * {@code (byte[], int)}, where the {@code int} coordinate type 2272 * corresponds to an argument that is an index into a {@code byte[]} array. 2273 * The returned VarHandle accesses bytes at an index in a {@code byte[]} 2274 * array, composing bytes to or from a value of the component type of 2275 * {@code viewArrayClass} according to the given endianness. 2276 * <p> 2277 * The supported component types (variables types) are {@code short}, 2278 * {@code char}, {@code int}, {@code long}, {@code float} and 2279 * {@code double}. 2280 * <p> 2281 * Access of bytes at a given index will result in an 2282 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2283 * or greater than the {@code byte[]} array length minus the size (in bytes) 2284 * of {@code T}. 2285 * <p> 2286 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2287 * with respect to the underlying memory address, {@code A} say, associated 2288 * with the array and index. 2289 * If access is misaligned then access for anything other than the 2290 * {@code get} and {@code set} access modes will result in an 2291 * {@code IllegalStateException}. In such cases atomic access is only 2292 * guaranteed with respect to the largest power of two that divides the GCD 2293 * of {@code A} and the size (in bytes) of {@code T}. 2294 * If access is aligned then following access modes are supported and are 2295 * guaranteed to support atomic access: 2296 * <ul> 2297 * <li>read write access modes for all {@code T}, with the exception of 2298 * access modes {@code get} and {@code set} for {@code long} and 2299 * {@code double} on 32-bit platforms. 2300 * <li>atomic update access modes for {@code int}, {@code long}, 2301 * {@code float} or {@code double}. 2302 * (Future major platform releases of the JDK may support additional 2303 * types for certain currently unsupported access modes.) 2304 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2305 * (Future major platform releases of the JDK may support additional 2306 * numeric types for certain currently unsupported access modes.) 2307 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2308 * (Future major platform releases of the JDK may support additional 2309 * numeric types for certain currently unsupported access modes.) 2310 * </ul> 2311 * <p> 2312 * Misaligned access, and therefore atomicity guarantees, may be determined 2313 * for {@code byte[]} arrays without operating on a specific array. Given 2314 * an {@code index}, {@code T} and it's corresponding boxed type, 2315 * {@code T_BOX}, misalignment may be determined as follows: 2316 * <pre>{@code 2317 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2318 * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). 2319 * alignmentOffset(0, sizeOfT); 2320 * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; 2321 * boolean isMisaligned = misalignedAtIndex != 0; 2322 * }</pre> 2323 * <p> 2324 * If the variable type is {@code float} or {@code double} then atomic 2325 * update access modes compare values using their bitwise representation 2326 * (see {@link Float#floatToRawIntBits} and 2327 * {@link Double#doubleToRawLongBits}, respectively). 2328 * @param viewArrayClass the view array class, with a component type of 2329 * type {@code T} 2330 * @param byteOrder the endianness of the view array elements, as 2331 * stored in the underlying {@code byte} array 2332 * @return a VarHandle giving access to elements of a {@code byte[]} array 2333 * viewed as if elements corresponding to the components type of the view 2334 * array class 2335 * @throws NullPointerException if viewArrayClass or byteOrder is null 2336 * @throws IllegalArgumentException if viewArrayClass is not an array type 2337 * @throws UnsupportedOperationException if the component type of 2338 * viewArrayClass is not supported as a variable type 2339 * @since 9 2340 */ 2341 public static byteArrayViewVarHandle(Class<?> viewArrayClass, ByteOrder byteOrder)2342 VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, 2343 ByteOrder byteOrder) throws IllegalArgumentException { 2344 checkClassIsArray(viewArrayClass); 2345 checkTypeIsViewable(viewArrayClass.getComponentType()); 2346 return ByteArrayViewVarHandle.create(viewArrayClass, byteOrder); 2347 } 2348 2349 /** 2350 * Produces a VarHandle giving access to elements of a {@code ByteBuffer} 2351 * viewed as if it were an array of elements of a different primitive 2352 * component type to that of {@code byte}, such as {@code int[]} or 2353 * {@code long[]}. 2354 * The VarHandle's variable type is the component type of 2355 * {@code viewArrayClass} and the list of coordinate types is 2356 * {@code (ByteBuffer, int)}, where the {@code int} coordinate type 2357 * corresponds to an argument that is an index into a {@code byte[]} array. 2358 * The returned VarHandle accesses bytes at an index in a 2359 * {@code ByteBuffer}, composing bytes to or from a value of the component 2360 * type of {@code viewArrayClass} according to the given endianness. 2361 * <p> 2362 * The supported component types (variables types) are {@code short}, 2363 * {@code char}, {@code int}, {@code long}, {@code float} and 2364 * {@code double}. 2365 * <p> 2366 * Access will result in a {@code ReadOnlyBufferException} for anything 2367 * other than the read access modes if the {@code ByteBuffer} is read-only. 2368 * <p> 2369 * Access of bytes at a given index will result in an 2370 * {@code IndexOutOfBoundsException} if the index is less than {@code 0} 2371 * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of 2372 * {@code T}. 2373 * <p> 2374 * Access of bytes at an index may be aligned or misaligned for {@code T}, 2375 * with respect to the underlying memory address, {@code A} say, associated 2376 * with the {@code ByteBuffer} and index. 2377 * If access is misaligned then access for anything other than the 2378 * {@code get} and {@code set} access modes will result in an 2379 * {@code IllegalStateException}. In such cases atomic access is only 2380 * guaranteed with respect to the largest power of two that divides the GCD 2381 * of {@code A} and the size (in bytes) of {@code T}. 2382 * If access is aligned then following access modes are supported and are 2383 * guaranteed to support atomic access: 2384 * <ul> 2385 * <li>read write access modes for all {@code T}, with the exception of 2386 * access modes {@code get} and {@code set} for {@code long} and 2387 * {@code double} on 32-bit platforms. 2388 * <li>atomic update access modes for {@code int}, {@code long}, 2389 * {@code float} or {@code double}. 2390 * (Future major platform releases of the JDK may support additional 2391 * types for certain currently unsupported access modes.) 2392 * <li>numeric atomic update access modes for {@code int} and {@code long}. 2393 * (Future major platform releases of the JDK may support additional 2394 * numeric types for certain currently unsupported access modes.) 2395 * <li>bitwise atomic update access modes for {@code int} and {@code long}. 2396 * (Future major platform releases of the JDK may support additional 2397 * numeric types for certain currently unsupported access modes.) 2398 * </ul> 2399 * <p> 2400 * Misaligned access, and therefore atomicity guarantees, may be determined 2401 * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an 2402 * {@code index}, {@code T} and it's corresponding boxed type, 2403 * {@code T_BOX}, as follows: 2404 * <pre>{@code 2405 * int sizeOfT = T_BOX.BYTES; // size in bytes of T 2406 * ByteBuffer bb = ... 2407 * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); 2408 * boolean isMisaligned = misalignedAtIndex != 0; 2409 * }</pre> 2410 * <p> 2411 * If the variable type is {@code float} or {@code double} then atomic 2412 * update access modes compare values using their bitwise representation 2413 * (see {@link Float#floatToRawIntBits} and 2414 * {@link Double#doubleToRawLongBits}, respectively). 2415 * @param viewArrayClass the view array class, with a component type of 2416 * type {@code T} 2417 * @param byteOrder the endianness of the view array elements, as 2418 * stored in the underlying {@code ByteBuffer} (Note this overrides the 2419 * endianness of a {@code ByteBuffer}) 2420 * @return a VarHandle giving access to elements of a {@code ByteBuffer} 2421 * viewed as if elements corresponding to the components type of the view 2422 * array class 2423 * @throws NullPointerException if viewArrayClass or byteOrder is null 2424 * @throws IllegalArgumentException if viewArrayClass is not an array type 2425 * @throws UnsupportedOperationException if the component type of 2426 * viewArrayClass is not supported as a variable type 2427 * @since 9 2428 */ 2429 public static byteBufferViewVarHandle(Class<?> viewArrayClass, ByteOrder byteOrder)2430 VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, 2431 ByteOrder byteOrder) throws IllegalArgumentException { 2432 checkClassIsArray(viewArrayClass); 2433 checkTypeIsViewable(viewArrayClass.getComponentType()); 2434 return ByteBufferViewVarHandle.create(viewArrayClass, byteOrder); 2435 } 2436 // END Android-changed: OpenJDK 9+181 VarHandle API factory methods. 2437 2438 /// method handle invocation (reflective style) 2439 2440 /** 2441 * Produces a method handle which will invoke any method handle of the 2442 * given {@code type}, with a given number of trailing arguments replaced by 2443 * a single trailing {@code Object[]} array. 2444 * The resulting invoker will be a method handle with the following 2445 * arguments: 2446 * <ul> 2447 * <li>a single {@code MethodHandle} target 2448 * <li>zero or more leading values (counted by {@code leadingArgCount}) 2449 * <li>an {@code Object[]} array containing trailing arguments 2450 * </ul> 2451 * <p> 2452 * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with 2453 * the indicated {@code type}. 2454 * That is, if the target is exactly of the given {@code type}, it will behave 2455 * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} 2456 * is used to convert the target to the required {@code type}. 2457 * <p> 2458 * The type of the returned invoker will not be the given {@code type}, but rather 2459 * will have all parameters except the first {@code leadingArgCount} 2460 * replaced by a single array of type {@code Object[]}, which will be 2461 * the final parameter. 2462 * <p> 2463 * Before invoking its target, the invoker will spread the final array, apply 2464 * reference casts as necessary, and unbox and widen primitive arguments. 2465 * If, when the invoker is called, the supplied array argument does 2466 * not have the correct number of elements, the invoker will throw 2467 * an {@link IllegalArgumentException} instead of invoking the target. 2468 * <p> 2469 * This method is equivalent to the following code (though it may be more efficient): 2470 * <blockquote><pre>{@code 2471 MethodHandle invoker = MethodHandles.invoker(type); 2472 int spreadArgCount = type.parameterCount() - leadingArgCount; 2473 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2474 return invoker; 2475 * }</pre></blockquote> 2476 * This method throws no reflective or security exceptions. 2477 * @param type the desired target type 2478 * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target 2479 * @return a method handle suitable for invoking any method handle of the given type 2480 * @throws NullPointerException if {@code type} is null 2481 * @throws IllegalArgumentException if {@code leadingArgCount} is not in 2482 * the range from 0 to {@code type.parameterCount()} inclusive, 2483 * or if the resulting method handle's type would have 2484 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2485 */ 2486 static public spreadInvoker(MethodType type, int leadingArgCount)2487 MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { 2488 if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) 2489 throw newIllegalArgumentException("bad argument count", leadingArgCount); 2490 2491 MethodHandle invoker = MethodHandles.invoker(type); 2492 int spreadArgCount = type.parameterCount() - leadingArgCount; 2493 invoker = invoker.asSpreader(Object[].class, spreadArgCount); 2494 return invoker; 2495 } 2496 2497 /** 2498 * Produces a special <em>invoker method handle</em> which can be used to 2499 * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. 2500 * The resulting invoker will have a type which is 2501 * exactly equal to the desired type, except that it will accept 2502 * an additional leading argument of type {@code MethodHandle}. 2503 * <p> 2504 * This method is equivalent to the following code (though it may be more efficient): 2505 * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} 2506 * 2507 * <p style="font-size:smaller;"> 2508 * <em>Discussion:</em> 2509 * Invoker method handles can be useful when working with variable method handles 2510 * of unknown types. 2511 * For example, to emulate an {@code invokeExact} call to a variable method 2512 * handle {@code M}, extract its type {@code T}, 2513 * look up the invoker method {@code X} for {@code T}, 2514 * and call the invoker method, as {@code X.invoke(T, A...)}. 2515 * (It would not work to call {@code X.invokeExact}, since the type {@code T} 2516 * is unknown.) 2517 * If spreading, collecting, or other argument transformations are required, 2518 * they can be applied once to the invoker {@code X} and reused on many {@code M} 2519 * method handle values, as long as they are compatible with the type of {@code X}. 2520 * <p style="font-size:smaller;"> 2521 * <em>(Note: The invoker method is not available via the Core Reflection API. 2522 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2523 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2524 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2525 * <p> 2526 * This method throws no reflective or security exceptions. 2527 * @param type the desired target type 2528 * @return a method handle suitable for invoking any method handle of the given type 2529 * @throws IllegalArgumentException if the resulting method handle's type would have 2530 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2531 */ 2532 static public exactInvoker(MethodType type)2533 MethodHandle exactInvoker(MethodType type) { 2534 return new Transformers.Invoker(type, true /* isExactInvoker */); 2535 } 2536 2537 /** 2538 * Produces a special <em>invoker method handle</em> which can be used to 2539 * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. 2540 * The resulting invoker will have a type which is 2541 * exactly equal to the desired type, except that it will accept 2542 * an additional leading argument of type {@code MethodHandle}. 2543 * <p> 2544 * Before invoking its target, if the target differs from the expected type, 2545 * the invoker will apply reference casts as 2546 * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. 2547 * Similarly, the return value will be converted as necessary. 2548 * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, 2549 * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. 2550 * <p> 2551 * This method is equivalent to the following code (though it may be more efficient): 2552 * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} 2553 * <p style="font-size:smaller;"> 2554 * <em>Discussion:</em> 2555 * A {@linkplain MethodType#genericMethodType general method type} is one which 2556 * mentions only {@code Object} arguments and return values. 2557 * An invoker for such a type is capable of calling any method handle 2558 * of the same arity as the general type. 2559 * <p style="font-size:smaller;"> 2560 * <em>(Note: The invoker method is not available via the Core Reflection API. 2561 * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} 2562 * on the declared {@code invokeExact} or {@code invoke} method will raise an 2563 * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> 2564 * <p> 2565 * This method throws no reflective or security exceptions. 2566 * @param type the desired target type 2567 * @return a method handle suitable for invoking any method handle convertible to the given type 2568 * @throws IllegalArgumentException if the resulting method handle's type would have 2569 * <a href="MethodHandle.html#maxarity">too many parameters</a> 2570 */ 2571 static public invoker(MethodType type)2572 MethodHandle invoker(MethodType type) { 2573 return new Transformers.Invoker(type, false /* isExactInvoker */); 2574 } 2575 2576 // BEGIN Android-added: resolver for VarHandle accessor methods. methodHandleForVarHandleAccessor(VarHandle.AccessMode accessMode, MethodType type, boolean isExactInvoker)2577 static private MethodHandle methodHandleForVarHandleAccessor(VarHandle.AccessMode accessMode, 2578 MethodType type, 2579 boolean isExactInvoker) { 2580 Class<?> refc = VarHandle.class; 2581 Method method; 2582 try { 2583 method = refc.getDeclaredMethod(accessMode.methodName(), Object[].class); 2584 } catch (NoSuchMethodException e) { 2585 throw new InternalError("No method for AccessMode " + accessMode, e); 2586 } 2587 MethodType methodType = type.insertParameterTypes(0, VarHandle.class); 2588 int kind = isExactInvoker ? MethodHandle.INVOKE_VAR_HANDLE_EXACT 2589 : MethodHandle.INVOKE_VAR_HANDLE; 2590 return new MethodHandleImpl(method.getArtMethod(), kind, methodType); 2591 } 2592 // END Android-added: resolver for VarHandle accessor methods. 2593 2594 /** 2595 * Produces a special <em>invoker method handle</em> which can be used to 2596 * invoke a signature-polymorphic access mode method on any VarHandle whose 2597 * associated access mode type is compatible with the given type. 2598 * The resulting invoker will have a type which is exactly equal to the 2599 * desired given type, except that it will accept an additional leading 2600 * argument of type {@code VarHandle}. 2601 * 2602 * @param accessMode the VarHandle access mode 2603 * @param type the desired target type 2604 * @return a method handle suitable for invoking an access mode method of 2605 * any VarHandle whose access mode type is of the given type. 2606 * @since 9 2607 */ 2608 static public varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type)2609 MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2610 return methodHandleForVarHandleAccessor(accessMode, type, true /* isExactInvoker */); 2611 } 2612 2613 /** 2614 * Produces a special <em>invoker method handle</em> which can be used to 2615 * invoke a signature-polymorphic access mode method on any VarHandle whose 2616 * associated access mode type is compatible with the given type. 2617 * The resulting invoker will have a type which is exactly equal to the 2618 * desired given type, except that it will accept an additional leading 2619 * argument of type {@code VarHandle}. 2620 * <p> 2621 * Before invoking its target, if the access mode type differs from the 2622 * desired given type, the invoker will apply reference casts as necessary 2623 * and box, unbox, or widen primitive values, as if by 2624 * {@link MethodHandle#asType asType}. Similarly, the return value will be 2625 * converted as necessary. 2626 * <p> 2627 * This method is equivalent to the following code (though it may be more 2628 * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} 2629 * 2630 * @param accessMode the VarHandle access mode 2631 * @param type the desired target type 2632 * @return a method handle suitable for invoking an access mode method of 2633 * any VarHandle whose access mode type is convertible to the given 2634 * type. 2635 * @since 9 2636 */ 2637 static public varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type)2638 MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { 2639 return methodHandleForVarHandleAccessor(accessMode, type, false /* isExactInvoker */); 2640 } 2641 2642 // Android-changed: Basic invokers are not supported. 2643 // 2644 // static /*non-public*/ 2645 // MethodHandle basicInvoker(MethodType type) { 2646 // return type.invokers().basicInvoker(); 2647 // } 2648 2649 /// method handle modification (creation from other method handles) 2650 2651 /** 2652 * Produces a method handle which adapts the type of the 2653 * given method handle to a new type by pairwise argument and return type conversion. 2654 * The original type and new type must have the same number of arguments. 2655 * The resulting method handle is guaranteed to report a type 2656 * which is equal to the desired new type. 2657 * <p> 2658 * If the original type and new type are equal, returns target. 2659 * <p> 2660 * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, 2661 * and some additional conversions are also applied if those conversions fail. 2662 * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied 2663 * if possible, before or instead of any conversions done by {@code asType}: 2664 * <ul> 2665 * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, 2666 * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. 2667 * (This treatment of interfaces follows the usage of the bytecode verifier.) 2668 * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, 2669 * the boolean is converted to a byte value, 1 for true, 0 for false. 2670 * (This treatment follows the usage of the bytecode verifier.) 2671 * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, 2672 * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), 2673 * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. 2674 * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, 2675 * then a Java casting conversion (JLS 5.5) is applied. 2676 * (Specifically, <em>T0</em> will convert to <em>T1</em> by 2677 * widening and/or narrowing.) 2678 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing 2679 * conversion will be applied at runtime, possibly followed 2680 * by a Java casting conversion (JLS 5.5) on the primitive value, 2681 * possibly followed by a conversion from byte to boolean by testing 2682 * the low-order bit. 2683 * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, 2684 * and if the reference is null at runtime, a zero value is introduced. 2685 * </ul> 2686 * @param target the method handle to invoke after arguments are retyped 2687 * @param newType the expected type of the new method handle 2688 * @return a method handle which delegates to the target after performing 2689 * any necessary argument conversions, and arranges for any 2690 * necessary return value conversions 2691 * @throws NullPointerException if either argument is null 2692 * @throws WrongMethodTypeException if the conversion cannot be made 2693 * @see MethodHandle#asType 2694 */ 2695 public static explicitCastArguments(MethodHandle target, MethodType newType)2696 MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { 2697 explicitCastArgumentsChecks(target, newType); 2698 // use the asTypeCache when possible: 2699 MethodType oldType = target.type(); 2700 if (oldType == newType) return target; 2701 if (oldType.explicitCastEquivalentToAsType(newType)) { 2702 if (Transformers.Transformer.class.isAssignableFrom(target.getClass())) { 2703 // The StackFrameReader and StackFrameWriter used to perform transforms on 2704 // EmulatedStackFrames (in Transformers.java) do not how to perform asType() 2705 // conversions, but we know here that an explicit cast transform is the same as 2706 // having called asType() on the method handle. 2707 return new Transformers.ExplicitCastArguments(target.asFixedArity(), newType); 2708 } else { 2709 // Runtime will perform asType() conversion during invocation. 2710 return target.asFixedArity().asType(newType); 2711 } 2712 } 2713 return new Transformers.ExplicitCastArguments(target, newType); 2714 } 2715 explicitCastArgumentsChecks(MethodHandle target, MethodType newType)2716 private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { 2717 if (target.type().parameterCount() != newType.parameterCount()) { 2718 throw new WrongMethodTypeException("cannot explicitly cast " + target + 2719 " to " + newType); 2720 } 2721 } 2722 2723 /** 2724 * Produces a method handle which adapts the calling sequence of the 2725 * given method handle to a new type, by reordering the arguments. 2726 * The resulting method handle is guaranteed to report a type 2727 * which is equal to the desired new type. 2728 * <p> 2729 * The given array controls the reordering. 2730 * Call {@code #I} the number of incoming parameters (the value 2731 * {@code newType.parameterCount()}, and call {@code #O} the number 2732 * of outgoing parameters (the value {@code target.type().parameterCount()}). 2733 * Then the length of the reordering array must be {@code #O}, 2734 * and each element must be a non-negative number less than {@code #I}. 2735 * For every {@code N} less than {@code #O}, the {@code N}-th 2736 * outgoing argument will be taken from the {@code I}-th incoming 2737 * argument, where {@code I} is {@code reorder[N]}. 2738 * <p> 2739 * No argument or return value conversions are applied. 2740 * The type of each incoming argument, as determined by {@code newType}, 2741 * must be identical to the type of the corresponding outgoing parameter 2742 * or parameters in the target method handle. 2743 * The return type of {@code newType} must be identical to the return 2744 * type of the original target. 2745 * <p> 2746 * The reordering array need not specify an actual permutation. 2747 * An incoming argument will be duplicated if its index appears 2748 * more than once in the array, and an incoming argument will be dropped 2749 * if its index does not appear in the array. 2750 * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, 2751 * incoming arguments which are not mentioned in the reordering array 2752 * are may be any type, as determined only by {@code newType}. 2753 * <blockquote><pre>{@code 2754 import static java.lang.invoke.MethodHandles.*; 2755 import static java.lang.invoke.MethodType.*; 2756 ... 2757 MethodType intfn1 = methodType(int.class, int.class); 2758 MethodType intfn2 = methodType(int.class, int.class, int.class); 2759 MethodHandle sub = ... (int x, int y) -> (x-y) ...; 2760 assert(sub.type().equals(intfn2)); 2761 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); 2762 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); 2763 assert((int)rsub.invokeExact(1, 100) == 99); 2764 MethodHandle add = ... (int x, int y) -> (x+y) ...; 2765 assert(add.type().equals(intfn2)); 2766 MethodHandle twice = permuteArguments(add, intfn1, 0, 0); 2767 assert(twice.type().equals(intfn1)); 2768 assert((int)twice.invokeExact(21) == 42); 2769 * }</pre></blockquote> 2770 * @param target the method handle to invoke after arguments are reordered 2771 * @param newType the expected type of the new method handle 2772 * @param reorder an index array which controls the reordering 2773 * @return a method handle which delegates to the target after it 2774 * drops unused arguments and moves and/or duplicates the other arguments 2775 * @throws NullPointerException if any argument is null 2776 * @throws IllegalArgumentException if the index array length is not equal to 2777 * the arity of the target, or if any index array element 2778 * not a valid index for a parameter of {@code newType}, 2779 * or if two corresponding parameter types in 2780 * {@code target.type()} and {@code newType} are not identical, 2781 */ 2782 public static permuteArguments(MethodHandle target, MethodType newType, int... reorder)2783 MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { 2784 reorder = reorder.clone(); // get a private copy 2785 MethodType oldType = target.type(); 2786 permuteArgumentChecks(reorder, newType, oldType); 2787 2788 return new Transformers.PermuteArguments(newType, target, reorder); 2789 } 2790 2791 // Android-changed: findFirstDupOrDrop is unused and removed. 2792 // private static int findFirstDupOrDrop(int[] reorder, int newArity); 2793 permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType)2794 private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { 2795 if (newType.returnType() != oldType.returnType()) 2796 throw newIllegalArgumentException("return types do not match", 2797 oldType, newType); 2798 if (reorder.length == oldType.parameterCount()) { 2799 int limit = newType.parameterCount(); 2800 boolean bad = false; 2801 for (int j = 0; j < reorder.length; j++) { 2802 int i = reorder[j]; 2803 if (i < 0 || i >= limit) { 2804 bad = true; break; 2805 } 2806 Class<?> src = newType.parameterType(i); 2807 Class<?> dst = oldType.parameterType(j); 2808 if (src != dst) 2809 throw newIllegalArgumentException("parameter types do not match after reorder", 2810 oldType, newType); 2811 } 2812 if (!bad) return true; 2813 } 2814 throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); 2815 } 2816 2817 /** 2818 * Produces a method handle of the requested return type which returns the given 2819 * constant value every time it is invoked. 2820 * <p> 2821 * Before the method handle is returned, the passed-in value is converted to the requested type. 2822 * If the requested type is primitive, widening primitive conversions are attempted, 2823 * else reference conversions are attempted. 2824 * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. 2825 * @param type the return type of the desired method handle 2826 * @param value the value to return 2827 * @return a method handle of the given return type and no arguments, which always returns the given value 2828 * @throws NullPointerException if the {@code type} argument is null 2829 * @throws ClassCastException if the value cannot be converted to the required return type 2830 * @throws IllegalArgumentException if the given type is {@code void.class} 2831 */ 2832 public static constant(Class<?> type, Object value)2833 MethodHandle constant(Class<?> type, Object value) { 2834 if (type.isPrimitive()) { 2835 if (type == void.class) 2836 throw newIllegalArgumentException("void type"); 2837 Wrapper w = Wrapper.forPrimitiveType(type); 2838 value = w.convert(value, type); 2839 if (w.zero().equals(value)) 2840 return zero(w, type); 2841 return insertArguments(identity(type), 0, value); 2842 } else { 2843 if (value == null) 2844 return zero(Wrapper.OBJECT, type); 2845 return identity(type).bindTo(value); 2846 } 2847 } 2848 2849 /** 2850 * Produces a method handle which returns its sole argument when invoked. 2851 * @param type the type of the sole parameter and return value of the desired method handle 2852 * @return a unary method handle which accepts and returns the given type 2853 * @throws NullPointerException if the argument is null 2854 * @throws IllegalArgumentException if the given type is {@code void.class} 2855 */ 2856 public static identity(Class<?> type)2857 MethodHandle identity(Class<?> type) { 2858 // Android-added: explicit non-null check. 2859 Objects.requireNonNull(type); 2860 Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); 2861 int pos = btw.ordinal(); 2862 MethodHandle ident = IDENTITY_MHS[pos]; 2863 if (ident == null) { 2864 ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); 2865 } 2866 if (ident.type().returnType() == type) 2867 return ident; 2868 // something like identity(Foo.class); do not bother to intern these 2869 assert (btw == Wrapper.OBJECT); 2870 return makeIdentity(type); 2871 } 2872 2873 /** 2874 * Produces a constant method handle of the requested return type which 2875 * returns the default value for that type every time it is invoked. 2876 * The resulting constant method handle will have no side effects. 2877 * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. 2878 * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, 2879 * since {@code explicitCastArguments} converts {@code null} to default values. 2880 * @param type the expected return type of the desired method handle 2881 * @return a constant method handle that takes no arguments 2882 * and returns the default value of the given type (or void, if the type is void) 2883 * @throws NullPointerException if the argument is null 2884 * @see MethodHandles#constant 2885 * @see MethodHandles#empty 2886 * @see MethodHandles#explicitCastArguments 2887 * @since 9 2888 */ zero(Class<?> type)2889 public static MethodHandle zero(Class<?> type) { 2890 Objects.requireNonNull(type); 2891 return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); 2892 } 2893 identityOrVoid(Class<?> type)2894 private static MethodHandle identityOrVoid(Class<?> type) { 2895 return type == void.class ? zero(type) : identity(type); 2896 } 2897 2898 /** 2899 * Produces a method handle of the requested type which ignores any arguments, does nothing, 2900 * and returns a suitable default depending on the return type. 2901 * That is, it returns a zero primitive value, a {@code null}, or {@code void}. 2902 * <p>The returned method handle is equivalent to 2903 * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. 2904 * 2905 * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as 2906 * {@code guardWithTest(pred, target, empty(target.type())}. 2907 * @param type the type of the desired method handle 2908 * @return a constant method handle of the given type, which returns a default value of the given return type 2909 * @throws NullPointerException if the argument is null 2910 * @see MethodHandles#zero 2911 * @see MethodHandles#constant 2912 * @since 9 2913 */ empty(MethodType type)2914 public static MethodHandle empty(MethodType type) { 2915 Objects.requireNonNull(type); 2916 return dropArguments(zero(type.returnType()), 0, type.parameterList()); 2917 } 2918 2919 private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; makeIdentity(Class<?> ptype)2920 private static MethodHandle makeIdentity(Class<?> ptype) { 2921 // Android-changed: Android implementation using identity() functions and transformers. 2922 // MethodType mtype = methodType(ptype, ptype); 2923 // LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); 2924 // return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); 2925 if (ptype.isPrimitive()) { 2926 try { 2927 final MethodType mt = methodType(ptype, ptype); 2928 return Lookup.PUBLIC_LOOKUP.findStatic(MethodHandles.class, "identity", mt); 2929 } catch (NoSuchMethodException | IllegalAccessException e) { 2930 throw new AssertionError(e); 2931 } 2932 } else { 2933 return new Transformers.ReferenceIdentity(ptype); 2934 } 2935 } 2936 2937 // Android-added: helper methods for identity(). identity(byte val)2938 /** @hide */ public static byte identity(byte val) { return val; } identity(boolean val)2939 /** @hide */ public static boolean identity(boolean val) { return val; } identity(char val)2940 /** @hide */ public static char identity(char val) { return val; } identity(short val)2941 /** @hide */ public static short identity(short val) { return val; } identity(int val)2942 /** @hide */ public static int identity(int val) { return val; } identity(long val)2943 /** @hide */ public static long identity(long val) { return val; } identity(float val)2944 /** @hide */ public static float identity(float val) { return val; } identity(double val)2945 /** @hide */ public static double identity(double val) { return val; } 2946 zero(Wrapper btw, Class<?> rtype)2947 private static MethodHandle zero(Wrapper btw, Class<?> rtype) { 2948 int pos = btw.ordinal(); 2949 MethodHandle zero = ZERO_MHS[pos]; 2950 if (zero == null) { 2951 zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); 2952 } 2953 if (zero.type().returnType() == rtype) 2954 return zero; 2955 assert(btw == Wrapper.OBJECT); 2956 return makeZero(rtype); 2957 } 2958 private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; makeZero(Class<?> rtype)2959 private static MethodHandle makeZero(Class<?> rtype) { 2960 // Android-changed: use Android specific implementation. 2961 // MethodType mtype = methodType(rtype); 2962 // LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); 2963 // return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); 2964 return new Transformers.ZeroValue(rtype); 2965 } 2966 setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value)2967 private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { 2968 // Simulate a CAS, to avoid racy duplication of results. 2969 MethodHandle prev = cache[pos]; 2970 if (prev != null) return prev; 2971 return cache[pos] = value; 2972 } 2973 2974 /** 2975 * Provides a target method handle with one or more <em>bound arguments</em> 2976 * in advance of the method handle's invocation. 2977 * The formal parameters to the target corresponding to the bound 2978 * arguments are called <em>bound parameters</em>. 2979 * Returns a new method handle which saves away the bound arguments. 2980 * When it is invoked, it receives arguments for any non-bound parameters, 2981 * binds the saved arguments to their corresponding parameters, 2982 * and calls the original target. 2983 * <p> 2984 * The type of the new method handle will drop the types for the bound 2985 * parameters from the original target type, since the new method handle 2986 * will no longer require those arguments to be supplied by its callers. 2987 * <p> 2988 * Each given argument object must match the corresponding bound parameter type. 2989 * If a bound parameter type is a primitive, the argument object 2990 * must be a wrapper, and will be unboxed to produce the primitive value. 2991 * <p> 2992 * The {@code pos} argument selects which parameters are to be bound. 2993 * It may range between zero and <i>N-L</i> (inclusively), 2994 * where <i>N</i> is the arity of the target method handle 2995 * and <i>L</i> is the length of the values array. 2996 * @param target the method handle to invoke after the argument is inserted 2997 * @param pos where to insert the argument (zero for the first) 2998 * @param values the series of arguments to insert 2999 * @return a method handle which inserts an additional argument, 3000 * before calling the original method handle 3001 * @throws NullPointerException if the target or the {@code values} array is null 3002 * @see MethodHandle#bindTo 3003 */ 3004 public static insertArguments(MethodHandle target, int pos, Object... values)3005 MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { 3006 int insCount = values.length; 3007 Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); 3008 if (insCount == 0) { 3009 return target; 3010 } 3011 3012 // Throw ClassCastExceptions early if we can't cast any of the provided values 3013 // to the required type. 3014 for (int i = 0; i < insCount; i++) { 3015 final Class<?> ptype = ptypes[pos + i]; 3016 if (!ptype.isPrimitive()) { 3017 ptypes[pos + i].cast(values[i]); 3018 } else { 3019 // Will throw a ClassCastException if something terrible happens. 3020 values[i] = Wrapper.forPrimitiveType(ptype).convert(values[i], ptype); 3021 } 3022 } 3023 3024 return new Transformers.InsertArguments(target, pos, values); 3025 } 3026 3027 // Android-changed: insertArgumentPrimitive is unused. 3028 // 3029 // private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, 3030 // Class<?> ptype, Object value) { 3031 // Wrapper w = Wrapper.forPrimitiveType(ptype); 3032 // // perform unboxing and/or primitive conversion 3033 // value = w.convert(value, ptype); 3034 // switch (w) { 3035 // case INT: return result.bindArgumentI(pos, (int)value); 3036 // case LONG: return result.bindArgumentJ(pos, (long)value); 3037 // case FLOAT: return result.bindArgumentF(pos, (float)value); 3038 // case DOUBLE: return result.bindArgumentD(pos, (double)value); 3039 // default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); 3040 // } 3041 // } 3042 insertArgumentsChecks(MethodHandle target, int insCount, int pos)3043 private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { 3044 MethodType oldType = target.type(); 3045 int outargs = oldType.parameterCount(); 3046 int inargs = outargs - insCount; 3047 if (inargs < 0) 3048 throw newIllegalArgumentException("too many values to insert"); 3049 if (pos < 0 || pos > inargs) 3050 throw newIllegalArgumentException("no argument type to append"); 3051 return oldType.ptypes(); 3052 } 3053 3054 // Android-changed: inclusive language preference for 'placeholder'. 3055 /** 3056 * Produces a method handle which will discard some placeholder arguments 3057 * before calling some other specified <i>target</i> method handle. 3058 * The type of the new method handle will be the same as the target's type, 3059 * except it will also include the placeholder argument types, 3060 * at some given position. 3061 * <p> 3062 * The {@code pos} argument may range between zero and <i>N</i>, 3063 * where <i>N</i> is the arity of the target. 3064 * If {@code pos} is zero, the placeholder arguments will precede 3065 * the target's real arguments; if {@code pos} is <i>N</i> 3066 * they will come after. 3067 * <p> 3068 * <b>Example:</b> 3069 * <blockquote><pre>{@code 3070 import static java.lang.invoke.MethodHandles.*; 3071 import static java.lang.invoke.MethodType.*; 3072 ... 3073 MethodHandle cat = lookup().findVirtual(String.class, 3074 "concat", methodType(String.class, String.class)); 3075 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3076 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); 3077 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); 3078 assertEquals(bigType, d0.type()); 3079 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); 3080 * }</pre></blockquote> 3081 * <p> 3082 * This method is also equivalent to the following code: 3083 * <blockquote><pre> 3084 * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} 3085 * </pre></blockquote> 3086 * @param target the method handle to invoke after the arguments are dropped 3087 * @param valueTypes the type(s) of the argument(s) to drop 3088 * @param pos position of first argument to drop (zero for the leftmost) 3089 * @return a method handle which drops arguments of the given types, 3090 * before calling the original method handle 3091 * @throws NullPointerException if the target is null, 3092 * or if the {@code valueTypes} list or any of its elements is null 3093 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3094 * or if {@code pos} is negative or greater than the arity of the target, 3095 * or if the new method handle's type would have too many parameters 3096 */ 3097 public static dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes)3098 MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3099 return dropArguments0(target, pos, copyTypes(valueTypes.toArray())); 3100 } 3101 copyTypes(Object[] array)3102 private static List<Class<?>> copyTypes(Object[] array) { 3103 return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class)); 3104 } 3105 3106 private static dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes)3107 MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) { 3108 MethodType oldType = target.type(); // get NPE 3109 int dropped = dropArgumentChecks(oldType, pos, valueTypes); 3110 MethodType newType = oldType.insertParameterTypes(pos, valueTypes); 3111 if (dropped == 0) return target; 3112 // Android-changed: transformer implementation. 3113 // BoundMethodHandle result = target.rebind(); 3114 // LambdaForm lform = result.form; 3115 // int insertFormArg = 1 + pos; 3116 // for (Class<?> ptype : valueTypes) { 3117 // lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); 3118 // } 3119 // result = result.copyWith(newType, lform); 3120 // return result; 3121 return new Transformers.DropArguments(newType, target, pos, dropped); 3122 } 3123 dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes)3124 private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { 3125 int dropped = valueTypes.size(); 3126 MethodType.checkSlotCount(dropped); 3127 int outargs = oldType.parameterCount(); 3128 int inargs = outargs + dropped; 3129 if (pos < 0 || pos > outargs) 3130 throw newIllegalArgumentException("no argument type to remove" 3131 + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) 3132 ); 3133 return dropped; 3134 } 3135 3136 // Android-changed: inclusive language preference for 'placeholder'. 3137 /** 3138 * Produces a method handle which will discard some placeholder arguments 3139 * before calling some other specified <i>target</i> method handle. 3140 * The type of the new method handle will be the same as the target's type, 3141 * except it will also include the placeholder argument types, 3142 * at some given position. 3143 * <p> 3144 * The {@code pos} argument may range between zero and <i>N</i>, 3145 * where <i>N</i> is the arity of the target. 3146 * If {@code pos} is zero, the placeholder arguments will precede 3147 * the target's real arguments; if {@code pos} is <i>N</i> 3148 * they will come after. 3149 * @apiNote 3150 * <blockquote><pre>{@code 3151 import static java.lang.invoke.MethodHandles.*; 3152 import static java.lang.invoke.MethodType.*; 3153 ... 3154 MethodHandle cat = lookup().findVirtual(String.class, 3155 "concat", methodType(String.class, String.class)); 3156 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3157 MethodHandle d0 = dropArguments(cat, 0, String.class); 3158 assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); 3159 MethodHandle d1 = dropArguments(cat, 1, String.class); 3160 assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); 3161 MethodHandle d2 = dropArguments(cat, 2, String.class); 3162 assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); 3163 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); 3164 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); 3165 * }</pre></blockquote> 3166 * <p> 3167 * This method is also equivalent to the following code: 3168 * <blockquote><pre> 3169 * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} 3170 * </pre></blockquote> 3171 * @param target the method handle to invoke after the arguments are dropped 3172 * @param valueTypes the type(s) of the argument(s) to drop 3173 * @param pos position of first argument to drop (zero for the leftmost) 3174 * @return a method handle which drops arguments of the given types, 3175 * before calling the original method handle 3176 * @throws NullPointerException if the target is null, 3177 * or if the {@code valueTypes} array or any of its elements is null 3178 * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, 3179 * or if {@code pos} is negative or greater than the arity of the target, 3180 * or if the new method handle's type would have 3181 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3182 */ 3183 public static dropArguments(MethodHandle target, int pos, Class<?>... valueTypes)3184 MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { 3185 return dropArguments0(target, pos, copyTypes(valueTypes)); 3186 } 3187 3188 // private version which allows caller some freedom with error handling dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, boolean nullOnFailure)3189 private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, 3190 boolean nullOnFailure) { 3191 newTypes = copyTypes(newTypes.toArray()); 3192 List<Class<?>> oldTypes = target.type().parameterList(); 3193 int match = oldTypes.size(); 3194 if (skip != 0) { 3195 if (skip < 0 || skip > match) { 3196 throw newIllegalArgumentException("illegal skip", skip, target); 3197 } 3198 oldTypes = oldTypes.subList(skip, match); 3199 match -= skip; 3200 } 3201 List<Class<?>> addTypes = newTypes; 3202 int add = addTypes.size(); 3203 if (pos != 0) { 3204 if (pos < 0 || pos > add) { 3205 throw newIllegalArgumentException("illegal pos", pos, newTypes); 3206 } 3207 addTypes = addTypes.subList(pos, add); 3208 add -= pos; 3209 assert(addTypes.size() == add); 3210 } 3211 // Do not add types which already match the existing arguments. 3212 if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { 3213 if (nullOnFailure) { 3214 return null; 3215 } 3216 throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); 3217 } 3218 addTypes = addTypes.subList(match, add); 3219 add -= match; 3220 assert(addTypes.size() == add); 3221 // newTypes: ( P*[pos], M*[match], A*[add] ) 3222 // target: ( S*[skip], M*[match] ) 3223 MethodHandle adapter = target; 3224 if (add > 0) { 3225 adapter = dropArguments0(adapter, skip+ match, addTypes); 3226 } 3227 // adapter: (S*[skip], M*[match], A*[add] ) 3228 if (pos > 0) { 3229 adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos)); 3230 } 3231 // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) 3232 return adapter; 3233 } 3234 3235 // Android-changed: inclusive language preference for 'placeholder'. 3236 /** 3237 * Adapts a target method handle to match the given parameter type list. If necessary, adds placeholder arguments. Some 3238 * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter 3239 * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The 3240 * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before 3241 * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by 3242 * {@link #dropArguments(MethodHandle, int, Class[])}. 3243 * <p> 3244 * The resulting handle will have the same return type as the target handle. 3245 * <p> 3246 * In more formal terms, assume these two type lists:<ul> 3247 * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as 3248 * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list, 3249 * {@code newTypes}. 3250 * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as 3251 * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's 3252 * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching 3253 * sub-list. 3254 * </ul> 3255 * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type 3256 * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by 3257 * {@link #dropArguments(MethodHandle, int, Class[])}. 3258 * 3259 * @apiNote 3260 * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be 3261 * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows: 3262 * <blockquote><pre>{@code 3263 import static java.lang.invoke.MethodHandles.*; 3264 import static java.lang.invoke.MethodType.*; 3265 ... 3266 ... 3267 MethodHandle h0 = constant(boolean.class, true); 3268 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); 3269 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); 3270 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); 3271 if (h1.type().parameterCount() < h2.type().parameterCount()) 3272 h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 3273 else 3274 h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 3275 MethodHandle h3 = guardWithTest(h0, h1, h2); 3276 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); 3277 * }</pre></blockquote> 3278 * @param target the method handle to adapt 3279 * @param skip number of targets parameters to disregard (they will be unchanged) 3280 * @param newTypes the list of types to match {@code target}'s parameter type list to 3281 * @param pos place in {@code newTypes} where the non-skipped target parameters must occur 3282 * @return a possibly adapted method handle 3283 * @throws NullPointerException if either argument is null 3284 * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, 3285 * or if {@code skip} is negative or greater than the arity of the target, 3286 * or if {@code pos} is negative or greater than the newTypes list size, 3287 * or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position 3288 * {@code pos}. 3289 * @since 9 3290 */ 3291 public static dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos)3292 MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { 3293 Objects.requireNonNull(target); 3294 Objects.requireNonNull(newTypes); 3295 return dropArgumentsToMatch(target, skip, newTypes, pos, false); 3296 } 3297 3298 /** 3299 * Adapts a target method handle by pre-processing 3300 * one or more of its arguments, each with its own unary filter function, 3301 * and then calling the target with each pre-processed argument 3302 * replaced by the result of its corresponding filter function. 3303 * <p> 3304 * The pre-processing is performed by one or more method handles, 3305 * specified in the elements of the {@code filters} array. 3306 * The first element of the filter array corresponds to the {@code pos} 3307 * argument of the target, and so on in sequence. 3308 * The filter functions are invoked in left to right order. 3309 * <p> 3310 * Null arguments in the array are treated as identity functions, 3311 * and the corresponding arguments left unchanged. 3312 * (If there are no non-null elements in the array, the original target is returned.) 3313 * Each filter is applied to the corresponding argument of the adapter. 3314 * <p> 3315 * If a filter {@code F} applies to the {@code N}th argument of 3316 * the target, then {@code F} must be a method handle which 3317 * takes exactly one argument. The type of {@code F}'s sole argument 3318 * replaces the corresponding argument type of the target 3319 * in the resulting adapted method handle. 3320 * The return type of {@code F} must be identical to the corresponding 3321 * parameter type of the target. 3322 * <p> 3323 * It is an error if there are elements of {@code filters} 3324 * (null or not) 3325 * which do not correspond to argument positions in the target. 3326 * <p><b>Example:</b> 3327 * <blockquote><pre>{@code 3328 import static java.lang.invoke.MethodHandles.*; 3329 import static java.lang.invoke.MethodType.*; 3330 ... 3331 MethodHandle cat = lookup().findVirtual(String.class, 3332 "concat", methodType(String.class, String.class)); 3333 MethodHandle upcase = lookup().findVirtual(String.class, 3334 "toUpperCase", methodType(String.class)); 3335 assertEquals("xy", (String) cat.invokeExact("x", "y")); 3336 MethodHandle f0 = filterArguments(cat, 0, upcase); 3337 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy 3338 MethodHandle f1 = filterArguments(cat, 1, upcase); 3339 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY 3340 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); 3341 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY 3342 * }</pre></blockquote> 3343 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3344 * denotes the return type of both the {@code target} and resulting adapter. 3345 * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values 3346 * of the parameters and arguments that precede and follow the filter position 3347 * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and 3348 * values of the filtered parameters and arguments; they also represent the 3349 * return types of the {@code filter[i]} handles. The latter accept arguments 3350 * {@code v[i]} of type {@code V[i]}, which also appear in the signature of 3351 * the resulting adapter. 3352 * <blockquote><pre>{@code 3353 * T target(P... p, A[i]... a[i], B... b); 3354 * A[i] filter[i](V[i]); 3355 * T adapter(P... p, V[i]... v[i], B... b) { 3356 * return target(p..., filter[i](v[i])..., b...); 3357 * } 3358 * }</pre></blockquote> 3359 * <p> 3360 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3361 * variable-arity method handle}, even if the original target method handle was. 3362 * 3363 * @param target the method handle to invoke after arguments are filtered 3364 * @param pos the position of the first argument to filter 3365 * @param filters method handles to call initially on filtered arguments 3366 * @return method handle which incorporates the specified argument filtering logic 3367 * @throws NullPointerException if the target is null 3368 * or if the {@code filters} array is null 3369 * @throws IllegalArgumentException if a non-null element of {@code filters} 3370 * does not match a corresponding argument type of target as described above, 3371 * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, 3372 * or if the resulting method handle's type would have 3373 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3374 */ 3375 public static filterArguments(MethodHandle target, int pos, MethodHandle... filters)3376 MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { 3377 filterArgumentsCheckArity(target, pos, filters); 3378 MethodHandle adapter = target; 3379 // Android-changed: transformer implementation. 3380 // process filters in reverse order so that the invocation of 3381 // the resulting adapter will invoke the filters in left-to-right order 3382 // for (int i = filters.length - 1; i >= 0; --i) { 3383 // MethodHandle filter = filters[i]; 3384 // if (filter == null) continue; // ignore null elements of filters 3385 // adapter = filterArgument(adapter, pos + i, filter); 3386 // } 3387 // return adapter; 3388 for (int i = 0; i < filters.length; ++i) { 3389 filterArgumentChecks(target, i + pos, filters[i]); 3390 } 3391 return new Transformers.FilterArguments(target, pos, filters); 3392 } 3393 3394 /*non-public*/ static filterArgument(MethodHandle target, int pos, MethodHandle filter)3395 MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { 3396 filterArgumentChecks(target, pos, filter); 3397 // Android-changed: use Transformer implementation. 3398 // MethodType targetType = target.type(); 3399 // MethodType filterType = filter.type(); 3400 // BoundMethodHandle result = target.rebind(); 3401 // Class<?> newParamType = filterType.parameterType(0); 3402 // LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); 3403 // MethodType newType = targetType.changeParameterType(pos, newParamType); 3404 // result = result.copyWithExtendL(newType, lform, filter); 3405 // return result; 3406 return new Transformers.FilterArguments(target, pos, filter); 3407 } 3408 filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters)3409 private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { 3410 MethodType targetType = target.type(); 3411 int maxPos = targetType.parameterCount(); 3412 if (pos + filters.length > maxPos) 3413 throw newIllegalArgumentException("too many filters"); 3414 } 3415 filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter)3416 private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3417 MethodType targetType = target.type(); 3418 MethodType filterType = filter.type(); 3419 if (filterType.parameterCount() != 1 3420 || filterType.returnType() != targetType.parameterType(pos)) 3421 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3422 } 3423 3424 /** 3425 * Adapts a target method handle by pre-processing 3426 * a sub-sequence of its arguments with a filter (another method handle). 3427 * The pre-processed arguments are replaced by the result (if any) of the 3428 * filter function. 3429 * The target is then called on the modified (usually shortened) argument list. 3430 * <p> 3431 * If the filter returns a value, the target must accept that value as 3432 * its argument in position {@code pos}, preceded and/or followed by 3433 * any arguments not passed to the filter. 3434 * If the filter returns void, the target must accept all arguments 3435 * not passed to the filter. 3436 * No arguments are reordered, and a result returned from the filter 3437 * replaces (in order) the whole subsequence of arguments originally 3438 * passed to the adapter. 3439 * <p> 3440 * The argument types (if any) of the filter 3441 * replace zero or one argument types of the target, at position {@code pos}, 3442 * in the resulting adapted method handle. 3443 * The return type of the filter (if any) must be identical to the 3444 * argument type of the target at position {@code pos}, and that target argument 3445 * is supplied by the return value of the filter. 3446 * <p> 3447 * In all cases, {@code pos} must be greater than or equal to zero, and 3448 * {@code pos} must also be less than or equal to the target's arity. 3449 * <p><b>Example:</b> 3450 * <blockquote><pre>{@code 3451 import static java.lang.invoke.MethodHandles.*; 3452 import static java.lang.invoke.MethodType.*; 3453 ... 3454 MethodHandle deepToString = publicLookup() 3455 .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); 3456 3457 MethodHandle ts1 = deepToString.asCollector(String[].class, 1); 3458 assertEquals("[strange]", (String) ts1.invokeExact("strange")); 3459 3460 MethodHandle ts2 = deepToString.asCollector(String[].class, 2); 3461 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); 3462 3463 MethodHandle ts3 = deepToString.asCollector(String[].class, 3); 3464 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); 3465 assertEquals("[top, [up, down], strange]", 3466 (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); 3467 3468 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); 3469 assertEquals("[top, [up, down], [strange]]", 3470 (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); 3471 3472 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); 3473 assertEquals("[top, [[up, down, strange], charm], bottom]", 3474 (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); 3475 * }</pre></blockquote> 3476 * <p> Here is pseudocode for the resulting adapter: 3477 * <blockquote><pre>{@code 3478 * T target(A...,V,C...); 3479 * V filter(B...); 3480 * T adapter(A... a,B... b,C... c) { 3481 * V v = filter(b...); 3482 * return target(a...,v,c...); 3483 * } 3484 * // and if the filter has no arguments: 3485 * T target2(A...,V,C...); 3486 * V filter2(); 3487 * T adapter2(A... a,C... c) { 3488 * V v = filter2(); 3489 * return target2(a...,v,c...); 3490 * } 3491 * // and if the filter has a void return: 3492 * T target3(A...,C...); 3493 * void filter3(B...); 3494 * void adapter3(A... a,B... b,C... c) { 3495 * filter3(b...); 3496 * return target3(a...,c...); 3497 * } 3498 * }</pre></blockquote> 3499 * <p> 3500 * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to 3501 * one which first "folds" the affected arguments, and then drops them, in separate 3502 * steps as follows: 3503 * <blockquote><pre>{@code 3504 * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 3505 * mh = MethodHandles.foldArguments(mh, coll); //step 1 3506 * }</pre></blockquote> 3507 * If the target method handle consumes no arguments besides than the result 3508 * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} 3509 * is equivalent to {@code filterReturnValue(coll, mh)}. 3510 * If the filter method handle {@code coll} consumes one argument and produces 3511 * a non-void result, then {@code collectArguments(mh, N, coll)} 3512 * is equivalent to {@code filterArguments(mh, N, coll)}. 3513 * Other equivalences are possible but would require argument permutation. 3514 * 3515 * @param target the method handle to invoke after filtering the subsequence of arguments 3516 * @param pos the position of the first adapter argument to pass to the filter, 3517 * and/or the target argument which receives the result of the filter 3518 * @param filter method handle to call on the subsequence of arguments 3519 * @return method handle which incorporates the specified argument subsequence filtering logic 3520 * @throws NullPointerException if either argument is null 3521 * @throws IllegalArgumentException if the return type of {@code filter} 3522 * is non-void and is not the same as the {@code pos} argument of the target, 3523 * or if {@code pos} is not between 0 and the target's arity, inclusive, 3524 * or if the resulting method handle's type would have 3525 * <a href="MethodHandle.html#maxarity">too many parameters</a> 3526 * @see MethodHandles#foldArguments 3527 * @see MethodHandles#filterArguments 3528 * @see MethodHandles#filterReturnValue 3529 */ 3530 public static collectArguments(MethodHandle target, int pos, MethodHandle filter)3531 MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { 3532 MethodType newType = collectArgumentsChecks(target, pos, filter); 3533 return new Transformers.CollectArguments(target, filter, pos, newType); 3534 } 3535 collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter)3536 private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { 3537 MethodType targetType = target.type(); 3538 MethodType filterType = filter.type(); 3539 Class<?> rtype = filterType.returnType(); 3540 List<Class<?>> filterArgs = filterType.parameterList(); 3541 if (rtype == void.class) { 3542 return targetType.insertParameterTypes(pos, filterArgs); 3543 } 3544 if (rtype != targetType.parameterType(pos)) { 3545 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3546 } 3547 return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); 3548 } 3549 3550 /** 3551 * Adapts a target method handle by post-processing 3552 * its return value (if any) with a filter (another method handle). 3553 * The result of the filter is returned from the adapter. 3554 * <p> 3555 * If the target returns a value, the filter must accept that value as 3556 * its only argument. 3557 * If the target returns void, the filter must accept no arguments. 3558 * <p> 3559 * The return type of the filter 3560 * replaces the return type of the target 3561 * in the resulting adapted method handle. 3562 * The argument type of the filter (if any) must be identical to the 3563 * return type of the target. 3564 * <p><b>Example:</b> 3565 * <blockquote><pre>{@code 3566 import static java.lang.invoke.MethodHandles.*; 3567 import static java.lang.invoke.MethodType.*; 3568 ... 3569 MethodHandle cat = lookup().findVirtual(String.class, 3570 "concat", methodType(String.class, String.class)); 3571 MethodHandle length = lookup().findVirtual(String.class, 3572 "length", methodType(int.class)); 3573 System.out.println((String) cat.invokeExact("x", "y")); // xy 3574 MethodHandle f0 = filterReturnValue(cat, length); 3575 System.out.println((int) f0.invokeExact("x", "y")); // 2 3576 * }</pre></blockquote> 3577 * <p>Here is pseudocode for the resulting adapter. In the code, 3578 * {@code T}/{@code t} represent the result type and value of the 3579 * {@code target}; {@code V}, the result type of the {@code filter}; and 3580 * {@code A}/{@code a}, the types and values of the parameters and arguments 3581 * of the {@code target} as well as the resulting adapter. 3582 * <blockquote><pre>{@code 3583 * T target(A...); 3584 * V filter(T); 3585 * V adapter(A... a) { 3586 * T t = target(a...); 3587 * return filter(t); 3588 * } 3589 * // and if the target has a void return: 3590 * void target2(A...); 3591 * V filter2(); 3592 * V adapter2(A... a) { 3593 * target2(a...); 3594 * return filter2(); 3595 * } 3596 * // and if the filter has a void return: 3597 * T target3(A...); 3598 * void filter3(V); 3599 * void adapter3(A... a) { 3600 * T t = target3(a...); 3601 * filter3(t); 3602 * } 3603 * }</pre></blockquote> 3604 * <p> 3605 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3606 * variable-arity method handle}, even if the original target method handle was. 3607 * @param target the method handle to invoke before filtering the return value 3608 * @param filter method handle to call on the return value 3609 * @return method handle which incorporates the specified return value filtering logic 3610 * @throws NullPointerException if either argument is null 3611 * @throws IllegalArgumentException if the argument list of {@code filter} 3612 * does not match the return type of target as described above 3613 */ 3614 public static filterReturnValue(MethodHandle target, MethodHandle filter)3615 MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { 3616 MethodType targetType = target.type(); 3617 MethodType filterType = filter.type(); 3618 filterReturnValueChecks(targetType, filterType); 3619 // Android-changed: use a transformer. 3620 // BoundMethodHandle result = target.rebind(); 3621 // BasicType rtype = BasicType.basicType(filterType.returnType()); 3622 // LambdaForm lform = result.editor().filterReturnForm(rtype, false); 3623 // MethodType newType = targetType.changeReturnType(filterType.returnType()); 3624 // result = result.copyWithExtendL(newType, lform, filter); 3625 // return result; 3626 return new Transformers.FilterReturnValue(target, filter); 3627 } 3628 filterReturnValueChecks(MethodType targetType, MethodType filterType)3629 private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { 3630 Class<?> rtype = targetType.returnType(); 3631 int filterValues = filterType.parameterCount(); 3632 if (filterValues == 0 3633 ? (rtype != void.class) 3634 : (rtype != filterType.parameterType(0) || filterValues != 1)) 3635 throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); 3636 } 3637 3638 /** 3639 * Adapts a target method handle by pre-processing 3640 * some of its arguments, and then calling the target with 3641 * the result of the pre-processing, inserted into the original 3642 * sequence of arguments. 3643 * <p> 3644 * The pre-processing is performed by {@code combiner}, a second method handle. 3645 * Of the arguments passed to the adapter, the first {@code N} arguments 3646 * are copied to the combiner, which is then called. 3647 * (Here, {@code N} is defined as the parameter count of the combiner.) 3648 * After this, control passes to the target, with any result 3649 * from the combiner inserted before the original {@code N} incoming 3650 * arguments. 3651 * <p> 3652 * If the combiner returns a value, the first parameter type of the target 3653 * must be identical with the return type of the combiner, and the next 3654 * {@code N} parameter types of the target must exactly match the parameters 3655 * of the combiner. 3656 * <p> 3657 * If the combiner has a void return, no result will be inserted, 3658 * and the first {@code N} parameter types of the target 3659 * must exactly match the parameters of the combiner. 3660 * <p> 3661 * The resulting adapter is the same type as the target, except that the 3662 * first parameter type is dropped, 3663 * if it corresponds to the result of the combiner. 3664 * <p> 3665 * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments 3666 * that either the combiner or the target does not wish to receive. 3667 * If some of the incoming arguments are destined only for the combiner, 3668 * consider using {@link MethodHandle#asCollector asCollector} instead, since those 3669 * arguments will not need to be live on the stack on entry to the 3670 * target.) 3671 * <p><b>Example:</b> 3672 * <blockquote><pre>{@code 3673 import static java.lang.invoke.MethodHandles.*; 3674 import static java.lang.invoke.MethodType.*; 3675 ... 3676 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 3677 "println", methodType(void.class, String.class)) 3678 .bindTo(System.out); 3679 MethodHandle cat = lookup().findVirtual(String.class, 3680 "concat", methodType(String.class, String.class)); 3681 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 3682 MethodHandle catTrace = foldArguments(cat, trace); 3683 // also prints "boo": 3684 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 3685 * }</pre></blockquote> 3686 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3687 * represents the result type of the {@code target} and resulting adapter. 3688 * {@code V}/{@code v} represent the type and value of the parameter and argument 3689 * of {@code target} that precedes the folding position; {@code V} also is 3690 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 3691 * types and values of the {@code N} parameters and arguments at the folding 3692 * position. {@code B}/{@code b} represent the types and values of the 3693 * {@code target} parameters and arguments that follow the folded parameters 3694 * and arguments. 3695 * <blockquote><pre>{@code 3696 * // there are N arguments in A... 3697 * T target(V, A[N]..., B...); 3698 * V combiner(A...); 3699 * T adapter(A... a, B... b) { 3700 * V v = combiner(a...); 3701 * return target(v, a..., b...); 3702 * } 3703 * // and if the combiner has a void return: 3704 * T target2(A[N]..., B...); 3705 * void combiner2(A...); 3706 * T adapter2(A... a, B... b) { 3707 * combiner2(a...); 3708 * return target2(a..., b...); 3709 * } 3710 * }</pre></blockquote> 3711 * <p> 3712 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3713 * variable-arity method handle}, even if the original target method handle was. 3714 * @param target the method handle to invoke after arguments are combined 3715 * @param combiner method handle to call initially on the incoming arguments 3716 * @return method handle which incorporates the specified argument folding logic 3717 * @throws NullPointerException if either argument is null 3718 * @throws IllegalArgumentException if {@code combiner}'s return type 3719 * is non-void and not the same as the first argument type of 3720 * the target, or if the initial {@code N} argument types 3721 * of the target 3722 * (skipping one matching the {@code combiner}'s return type) 3723 * are not identical with the argument types of {@code combiner} 3724 */ 3725 public static foldArguments(MethodHandle target, MethodHandle combiner)3726 MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { 3727 return foldArguments(target, 0, combiner); 3728 } 3729 3730 /** 3731 * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then 3732 * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just 3733 * before the folded arguments. 3734 * <p> 3735 * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the 3736 * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a 3737 * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position 3738 * 0. 3739 * 3740 * @apiNote Example: 3741 * <blockquote><pre>{@code 3742 import static java.lang.invoke.MethodHandles.*; 3743 import static java.lang.invoke.MethodType.*; 3744 ... 3745 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, 3746 "println", methodType(void.class, String.class)) 3747 .bindTo(System.out); 3748 MethodHandle cat = lookup().findVirtual(String.class, 3749 "concat", methodType(String.class, String.class)); 3750 assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); 3751 MethodHandle catTrace = foldArguments(cat, 1, trace); 3752 // also prints "jum": 3753 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); 3754 * }</pre></blockquote> 3755 * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} 3756 * represents the result type of the {@code target} and resulting adapter. 3757 * {@code V}/{@code v} represent the type and value of the parameter and argument 3758 * of {@code target} that precedes the folding position; {@code V} also is 3759 * the result type of the {@code combiner}. {@code A}/{@code a} denote the 3760 * types and values of the {@code N} parameters and arguments at the folding 3761 * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types 3762 * and values of the {@code target} parameters and arguments that precede and 3763 * follow the folded parameters and arguments starting at {@code pos}, 3764 * respectively. 3765 * <blockquote><pre>{@code 3766 * // there are N arguments in A... 3767 * T target(Z..., V, A[N]..., B...); 3768 * V combiner(A...); 3769 * T adapter(Z... z, A... a, B... b) { 3770 * V v = combiner(a...); 3771 * return target(z..., v, a..., b...); 3772 * } 3773 * // and if the combiner has a void return: 3774 * T target2(Z..., A[N]..., B...); 3775 * void combiner2(A...); 3776 * T adapter2(Z... z, A... a, B... b) { 3777 * combiner2(a...); 3778 * return target2(z..., a..., b...); 3779 * } 3780 * }</pre></blockquote> 3781 * <p> 3782 * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector 3783 * variable-arity method handle}, even if the original target method handle was. 3784 * 3785 * @param target the method handle to invoke after arguments are combined 3786 * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code 3787 * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. 3788 * @param combiner method handle to call initially on the incoming arguments 3789 * @return method handle which incorporates the specified argument folding logic 3790 * @throws NullPointerException if either argument is null 3791 * @throws IllegalArgumentException if either of the following two conditions holds: 3792 * (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position 3793 * {@code pos} of the target signature; 3794 * (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching 3795 * the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}. 3796 * 3797 * @see #foldArguments(MethodHandle, MethodHandle) 3798 * @since 9 3799 */ 3800 public static foldArguments(MethodHandle target, int pos, MethodHandle combiner)3801 MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { 3802 MethodType targetType = target.type(); 3803 MethodType combinerType = combiner.type(); 3804 Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); 3805 // Android-changed: // Android-changed: transformer implementation. 3806 // BoundMethodHandle result = target.rebind(); 3807 // boolean dropResult = rtype == void.class; 3808 // LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); 3809 // MethodType newType = targetType; 3810 // if (!dropResult) { 3811 // newType = newType.dropParameterTypes(pos, pos + 1); 3812 // } 3813 // result = result.copyWithExtendL(newType, lform, combiner); 3814 // return result; 3815 3816 return new Transformers.FoldArguments(target, pos, combiner); 3817 } 3818 foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType)3819 private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { 3820 int foldArgs = combinerType.parameterCount(); 3821 Class<?> rtype = combinerType.returnType(); 3822 int foldVals = rtype == void.class ? 0 : 1; 3823 int afterInsertPos = foldPos + foldVals; 3824 boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); 3825 if (ok) { 3826 for (int i = 0; i < foldArgs; i++) { 3827 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { 3828 ok = false; 3829 break; 3830 } 3831 } 3832 } 3833 if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) 3834 ok = false; 3835 if (!ok) 3836 throw misMatchedTypes("target and combiner types", targetType, combinerType); 3837 return rtype; 3838 } 3839 3840 /** 3841 * Makes a method handle which adapts a target method handle, 3842 * by guarding it with a test, a boolean-valued method handle. 3843 * If the guard fails, a fallback handle is called instead. 3844 * All three method handles must have the same corresponding 3845 * argument and return types, except that the return type 3846 * of the test must be boolean, and the test is allowed 3847 * to have fewer arguments than the other two method handles. 3848 * <p> Here is pseudocode for the resulting adapter: 3849 * <blockquote><pre>{@code 3850 * boolean test(A...); 3851 * T target(A...,B...); 3852 * T fallback(A...,B...); 3853 * T adapter(A... a,B... b) { 3854 * if (test(a...)) 3855 * return target(a..., b...); 3856 * else 3857 * return fallback(a..., b...); 3858 * } 3859 * }</pre></blockquote> 3860 * Note that the test arguments ({@code a...} in the pseudocode) cannot 3861 * be modified by execution of the test, and so are passed unchanged 3862 * from the caller to the target or fallback as appropriate. 3863 * @param test method handle used for test, must return boolean 3864 * @param target method handle to call if test passes 3865 * @param fallback method handle to call if test fails 3866 * @return method handle which incorporates the specified if/then/else logic 3867 * @throws NullPointerException if any argument is null 3868 * @throws IllegalArgumentException if {@code test} does not return boolean, 3869 * or if all three method types do not match (with the return 3870 * type of {@code test} changed to match that of the target). 3871 */ 3872 public static guardWithTest(MethodHandle test, MethodHandle target, MethodHandle fallback)3873 MethodHandle guardWithTest(MethodHandle test, 3874 MethodHandle target, 3875 MethodHandle fallback) { 3876 MethodType gtype = test.type(); 3877 MethodType ttype = target.type(); 3878 MethodType ftype = fallback.type(); 3879 if (!ttype.equals(ftype)) 3880 throw misMatchedTypes("target and fallback types", ttype, ftype); 3881 if (gtype.returnType() != boolean.class) 3882 throw newIllegalArgumentException("guard type is not a predicate "+gtype); 3883 List<Class<?>> targs = ttype.parameterList(); 3884 List<Class<?>> gargs = gtype.parameterList(); 3885 if (!targs.equals(gargs)) { 3886 int gpc = gargs.size(), tpc = targs.size(); 3887 if (gpc >= tpc || !targs.subList(0, gpc).equals(gargs)) 3888 throw misMatchedTypes("target and test types", ttype, gtype); 3889 test = dropArguments(test, gpc, targs.subList(gpc, tpc)); 3890 gtype = test.type(); 3891 } 3892 3893 return new Transformers.GuardWithTest(test, target, fallback); 3894 } 3895 misMatchedTypes(String what, T t1, T t2)3896 static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { 3897 return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); 3898 } 3899 3900 /** 3901 * Makes a method handle which adapts a target method handle, 3902 * by running it inside an exception handler. 3903 * If the target returns normally, the adapter returns that value. 3904 * If an exception matching the specified type is thrown, the fallback 3905 * handle is called instead on the exception, plus the original arguments. 3906 * <p> 3907 * The target and handler must have the same corresponding 3908 * argument and return types, except that handler may omit trailing arguments 3909 * (similarly to the predicate in {@link #guardWithTest guardWithTest}). 3910 * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. 3911 * <p> 3912 * Here is pseudocode for the resulting adapter. In the code, {@code T} 3913 * represents the return type of the {@code target} and {@code handler}, 3914 * and correspondingly that of the resulting adapter; {@code A}/{@code a}, 3915 * the types and values of arguments to the resulting handle consumed by 3916 * {@code handler}; and {@code B}/{@code b}, those of arguments to the 3917 * resulting handle discarded by {@code handler}. 3918 * <blockquote><pre>{@code 3919 * T target(A..., B...); 3920 * T handler(ExType, A...); 3921 * T adapter(A... a, B... b) { 3922 * try { 3923 * return target(a..., b...); 3924 * } catch (ExType ex) { 3925 * return handler(ex, a...); 3926 * } 3927 * } 3928 * }</pre></blockquote> 3929 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 3930 * be modified by execution of the target, and so are passed unchanged 3931 * from the caller to the handler, if the handler is invoked. 3932 * <p> 3933 * The target and handler must return the same type, even if the handler 3934 * always throws. (This might happen, for instance, because the handler 3935 * is simulating a {@code finally} clause). 3936 * To create such a throwing handler, compose the handler creation logic 3937 * with {@link #throwException throwException}, 3938 * in order to create a method handle of the correct return type. 3939 * @param target method handle to call 3940 * @param exType the type of exception which the handler will catch 3941 * @param handler method handle to call if a matching exception is thrown 3942 * @return method handle which incorporates the specified try/catch logic 3943 * @throws NullPointerException if any argument is null 3944 * @throws IllegalArgumentException if {@code handler} does not accept 3945 * the given exception type, or if the method handle types do 3946 * not match in their return types and their 3947 * corresponding parameters 3948 * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) 3949 */ 3950 public static catchException(MethodHandle target, Class<? extends Throwable> exType, MethodHandle handler)3951 MethodHandle catchException(MethodHandle target, 3952 Class<? extends Throwable> exType, 3953 MethodHandle handler) { 3954 MethodType ttype = target.type(); 3955 MethodType htype = handler.type(); 3956 if (!Throwable.class.isAssignableFrom(exType)) 3957 throw new ClassCastException(exType.getName()); 3958 if (htype.parameterCount() < 1 || 3959 !htype.parameterType(0).isAssignableFrom(exType)) 3960 throw newIllegalArgumentException("handler does not accept exception type "+exType); 3961 if (htype.returnType() != ttype.returnType()) 3962 throw misMatchedTypes("target and handler return types", ttype, htype); 3963 handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); 3964 if (handler == null) { 3965 throw misMatchedTypes("target and handler types", ttype, htype); 3966 } 3967 // Android-changed: use Transformer implementation. 3968 // return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); 3969 return new Transformers.CatchException(target, handler, exType); 3970 } 3971 3972 /** 3973 * Produces a method handle which will throw exceptions of the given {@code exType}. 3974 * The method handle will accept a single argument of {@code exType}, 3975 * and immediately throw it as an exception. 3976 * The method type will nominally specify a return of {@code returnType}. 3977 * The return type may be anything convenient: It doesn't matter to the 3978 * method handle's behavior, since it will never return normally. 3979 * @param returnType the return type of the desired method handle 3980 * @param exType the parameter type of the desired method handle 3981 * @return method handle which can throw the given exceptions 3982 * @throws NullPointerException if either argument is null 3983 */ 3984 public static throwException(Class<?> returnType, Class<? extends Throwable> exType)3985 MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { 3986 if (!Throwable.class.isAssignableFrom(exType)) 3987 throw new ClassCastException(exType.getName()); 3988 // Android-changed: use Transformer implementation. 3989 // return MethodHandleImpl.throwException(methodType(returnType, exType)); 3990 return new Transformers.AlwaysThrow(returnType, exType); 3991 } 3992 3993 /** 3994 * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each 3995 * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and 3996 * delivers the loop's result, which is the return value of the resulting handle. 3997 * <p> 3998 * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop 3999 * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration 4000 * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in 4001 * terms of method handles, each clause will specify up to four independent actions:<ul> 4002 * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}. 4003 * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}. 4004 * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit. 4005 * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value. 4006 * </ul> 4007 * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}. 4008 * The values themselves will be {@code (v...)}. When we speak of "parameter lists", we will usually 4009 * be referring to types, but in some contexts (describing execution) the lists will be of actual values. 4010 * <p> 4011 * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in 4012 * this case. See below for a detailed description. 4013 * <p> 4014 * <em>Parameters optional everywhere:</em> 4015 * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}. 4016 * As an exception, the init functions cannot take any {@code v} parameters, 4017 * because those values are not yet computed when the init functions are executed. 4018 * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take. 4019 * In fact, any clause function may take no arguments at all. 4020 * <p> 4021 * <em>Loop parameters:</em> 4022 * A clause function may take all the iteration variable values it is entitled to, in which case 4023 * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>, 4024 * with their types and values notated as {@code (A...)} and {@code (a...)}. 4025 * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed. 4026 * (Since init functions do not accept iteration variables {@code v}, any parameter to an 4027 * init function is automatically a loop parameter {@code a}.) 4028 * As with iteration variables, clause functions are allowed but not required to accept loop parameters. 4029 * These loop parameters act as loop-invariant values visible across the whole loop. 4030 * <p> 4031 * <em>Parameters visible everywhere:</em> 4032 * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full 4033 * list {@code (v... a...)} of current iteration variable values and incoming loop parameters. 4034 * The init functions can observe initial pre-loop state, in the form {@code (a...)}. 4035 * Most clause functions will not need all of this information, but they will be formally connected to it 4036 * as if by {@link #dropArguments}. 4037 * <a id="astar"></a> 4038 * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full 4039 * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}). 4040 * In that notation, the general form of an init function parameter list 4041 * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}. 4042 * <p> 4043 * <em>Checking clause structure:</em> 4044 * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the 4045 * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" 4046 * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not 4047 * met by the inputs to the loop combinator. 4048 * <p> 4049 * <em>Effectively identical sequences:</em> 4050 * <a id="effid"></a> 4051 * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B} 4052 * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}. 4053 * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical" 4054 * as a whole if the set contains a longest list, and all members of the set are effectively identical to 4055 * that longest list. 4056 * For example, any set of type sequences of the form {@code (V*)} is effectively identical, 4057 * and the same is true if more sequences of the form {@code (V... A*)} are added. 4058 * <p> 4059 * <em>Step 0: Determine clause structure.</em><ol type="a"> 4060 * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element. 4061 * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. 4062 * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length 4063 * four. Padding takes place by appending elements to the array. 4064 * <li>Clauses with all {@code null}s are disregarded. 4065 * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". 4066 * </ol> 4067 * <p> 4068 * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a"> 4069 * <li>The iteration variable type for each clause is determined using the clause's init and step return types. 4070 * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is 4071 * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's 4072 * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's 4073 * iteration variable type. 4074 * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. 4075 * <li>This list of types is called the "iteration variable types" ({@code (V...)}). 4076 * </ol> 4077 * <p> 4078 * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul> 4079 * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}). 4080 * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types. 4081 * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.) 4082 * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types. 4083 * (These types will be checked in step 2, along with all the clause function types.) 4084 * <li>Omitted clause functions are ignored. (Equivalently, they are deemed to have empty parameter lists.) 4085 * <li>All of the collected parameter lists must be effectively identical. 4086 * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}). 4087 * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence. 4088 * <li>The combined list consisting of iteration variable types followed by the external parameter types is called 4089 * the "internal parameter list". 4090 * </ul> 4091 * <p> 4092 * <em>Step 1C: Determine loop return type.</em><ol type="a"> 4093 * <li>Examine fini function return types, disregarding omitted fini functions. 4094 * <li>If there are no fini functions, the loop return type is {@code void}. 4095 * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return 4096 * type. 4097 * </ol> 4098 * <p> 4099 * <em>Step 1D: Check other types.</em><ol type="a"> 4100 * <li>There must be at least one non-omitted pred function. 4101 * <li>Every non-omitted pred function must have a {@code boolean} return type. 4102 * </ol> 4103 * <p> 4104 * <em>Step 2: Determine parameter lists.</em><ol type="a"> 4105 * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}. 4106 * <li>The parameter list for init functions will be adjusted to the external parameter list. 4107 * (Note that their parameter lists are already effectively identical to this list.) 4108 * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be 4109 * effectively identical to the internal parameter list {@code (V... A...)}. 4110 * </ol> 4111 * <p> 4112 * <em>Step 3: Fill in omitted functions.</em><ol type="a"> 4113 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable 4114 * type. 4115 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration 4116 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} 4117 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) 4118 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far 4119 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.) 4120 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the 4121 * loop return type. 4122 * </ol> 4123 * <p> 4124 * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> 4125 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)}, 4126 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list. 4127 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter 4128 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list, 4129 * pad out the end of the list. 4130 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}. 4131 * </ol> 4132 * <p> 4133 * <em>Final observations.</em><ol type="a"> 4134 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. 4135 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have. 4136 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have. 4137 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of 4138 * (non-{@code void}) iteration variables {@code V} followed by loop parameters. 4139 * <li>Each pair of init and step functions agrees in their return type {@code V}. 4140 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables. 4141 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters. 4142 * </ol> 4143 * <p> 4144 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property: 4145 * <ul> 4146 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}. 4147 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters. 4148 * (Only one {@code Pn} has to be non-{@code null}.) 4149 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}. 4150 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types. 4151 * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}. 4152 * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}. 4153 * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine 4154 * the resulting loop handle's parameter types {@code (A...)}. 4155 * </ul> 4156 * In this example, the loop handle parameters {@code (A...)} were derived from the step functions, 4157 * which is natural if most of the loop computation happens in the steps. For some loops, 4158 * the burden of computation might be heaviest in the pred functions, and so the pred functions 4159 * might need to accept the loop parameter values. For loops with complex exit logic, the fini 4160 * functions might need to accept loop parameters, and likewise for loops with complex entry logic, 4161 * where the init functions will need the extra parameters. For such reasons, the rules for 4162 * determining these parameters are as symmetric as possible, across all clause parts. 4163 * In general, the loop parameters function as common invariant values across the whole 4164 * loop, while the iteration variables function as common variant values, or (if there is 4165 * no step function) as internal loop invariant temporaries. 4166 * <p> 4167 * <em>Loop execution.</em><ol type="a"> 4168 * <li>When the loop is called, the loop input values are saved in locals, to be passed to 4169 * every clause function. These locals are loop invariant. 4170 * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)}) 4171 * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals. 4172 * These locals will be loop varying (unless their steps behave as identity functions, as noted above). 4173 * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of 4174 * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)} 4175 * (in argument order). 4176 * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function 4177 * returns {@code false}. 4178 * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the 4179 * sequence {@code (v...)} of loop variables. 4180 * The updated value is immediately visible to all subsequent function calls. 4181 * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value 4182 * (of type {@code R}) is returned from the loop as a whole. 4183 * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit 4184 * except by throwing an exception. 4185 * </ol> 4186 * <p> 4187 * <em>Usage tips.</em> 4188 * <ul> 4189 * <li>Although each step function will receive the current values of <em>all</em> the loop variables, 4190 * sometimes a step function only needs to observe the current value of its own variable. 4191 * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}. 4192 * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}. 4193 * <li>Loop variables are not required to vary; they can be loop invariant. A clause can create 4194 * a loop invariant by a suitable init function with no step, pred, or fini function. This may be 4195 * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable. 4196 * <li>If some of the clause functions are virtual methods on an instance, the instance 4197 * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause 4198 * like {@code new MethodHandle[]{identity(ObjType.class)}}. In that case, the instance reference 4199 * will be the first iteration variable value, and it will be easy to use virtual 4200 * methods as clause parts, since all of them will take a leading instance reference matching that value. 4201 * </ul> 4202 * <p> 4203 * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types 4204 * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop; 4205 * and {@code R} is the common result type of all finalizers as well as of the resulting loop. 4206 * <blockquote><pre>{@code 4207 * V... init...(A...); 4208 * boolean pred...(V..., A...); 4209 * V... step...(V..., A...); 4210 * R fini...(V..., A...); 4211 * R loop(A... a) { 4212 * V... v... = init...(a...); 4213 * for (;;) { 4214 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { 4215 * v = s(v..., a...); 4216 * if (!p(v..., a...)) { 4217 * return f(v..., a...); 4218 * } 4219 * } 4220 * } 4221 * } 4222 * }</pre></blockquote> 4223 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded 4224 * to their full length, even though individual clause functions may neglect to take them all. 4225 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}. 4226 * 4227 * @apiNote Example: 4228 * <blockquote><pre>{@code 4229 * // iterative implementation of the factorial function as a loop handle 4230 * static int one(int k) { return 1; } 4231 * static int inc(int i, int acc, int k) { return i + 1; } 4232 * static int mult(int i, int acc, int k) { return i * acc; } 4233 * static boolean pred(int i, int acc, int k) { return i < k; } 4234 * static int fin(int i, int acc, int k) { return acc; } 4235 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4236 * // null initializer for counter, should initialize to 0 4237 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4238 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4239 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4240 * assertEquals(120, loop.invoke(5)); 4241 * }</pre></blockquote> 4242 * The same example, dropping arguments and using combinators: 4243 * <blockquote><pre>{@code 4244 * // simplified implementation of the factorial function as a loop handle 4245 * static int inc(int i) { return i + 1; } // drop acc, k 4246 * static int mult(int i, int acc) { return i * acc; } //drop k 4247 * static boolean cmp(int i, int k) { return i < k; } 4248 * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods 4249 * // null initializer for counter, should initialize to 0 4250 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 4251 * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc 4252 * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i 4253 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4254 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4255 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); 4256 * assertEquals(720, loop.invoke(6)); 4257 * }</pre></blockquote> 4258 * A similar example, using a helper object to hold a loop parameter: 4259 * <blockquote><pre>{@code 4260 * // instance-based implementation of the factorial function as a loop handle 4261 * static class FacLoop { 4262 * final int k; 4263 * FacLoop(int k) { this.k = k; } 4264 * int inc(int i) { return i + 1; } 4265 * int mult(int i, int acc) { return i * acc; } 4266 * boolean pred(int i) { return i < k; } 4267 * int fin(int i, int acc) { return acc; } 4268 * } 4269 * // assume MH_FacLoop is a handle to the constructor 4270 * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods 4271 * // null initializer for counter, should initialize to 0 4272 * MethodHandle MH_one = MethodHandles.constant(int.class, 1); 4273 * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop}; 4274 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; 4275 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; 4276 * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause); 4277 * assertEquals(5040, loop.invoke(7)); 4278 * }</pre></blockquote> 4279 * 4280 * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. 4281 * 4282 * @return a method handle embodying the looping behavior as defined by the arguments. 4283 * 4284 * @throws IllegalArgumentException in case any of the constraints described above is violated. 4285 * 4286 * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) 4287 * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4288 * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) 4289 * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) 4290 * @since 9 4291 */ loop(MethodHandle[].... clauses)4292 public static MethodHandle loop(MethodHandle[]... clauses) { 4293 // Step 0: determine clause structure. 4294 loopChecks0(clauses); 4295 4296 List<MethodHandle> init = new ArrayList<>(); 4297 List<MethodHandle> step = new ArrayList<>(); 4298 List<MethodHandle> pred = new ArrayList<>(); 4299 List<MethodHandle> fini = new ArrayList<>(); 4300 4301 Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { 4302 init.add(clause[0]); // all clauses have at least length 1 4303 step.add(clause.length <= 1 ? null : clause[1]); 4304 pred.add(clause.length <= 2 ? null : clause[2]); 4305 fini.add(clause.length <= 3 ? null : clause[3]); 4306 }); 4307 4308 assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; 4309 final int nclauses = init.size(); 4310 4311 // Step 1A: determine iteration variables (V...). 4312 final List<Class<?>> iterationVariableTypes = new ArrayList<>(); 4313 for (int i = 0; i < nclauses; ++i) { 4314 MethodHandle in = init.get(i); 4315 MethodHandle st = step.get(i); 4316 if (in == null && st == null) { 4317 iterationVariableTypes.add(void.class); 4318 } else if (in != null && st != null) { 4319 loopChecks1a(i, in, st); 4320 iterationVariableTypes.add(in.type().returnType()); 4321 } else { 4322 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); 4323 } 4324 } 4325 final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). 4326 collect(Collectors.toList()); 4327 4328 // Step 1B: determine loop parameters (A...). 4329 final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); 4330 loopChecks1b(init, commonSuffix); 4331 4332 // Step 1C: determine loop return type. 4333 // Step 1D: check other types. 4334 // local variable required here; see JDK-8223553 4335 Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type) 4336 .map(MethodType::returnType); 4337 final Class<?> loopReturnType = cstream.findFirst().orElse(void.class); 4338 loopChecks1cd(pred, fini, loopReturnType); 4339 4340 // Step 2: determine parameter lists. 4341 final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); 4342 commonParameterSequence.addAll(commonSuffix); 4343 loopChecks2(step, pred, fini, commonParameterSequence); 4344 4345 // Step 3: fill in omitted functions. 4346 for (int i = 0; i < nclauses; ++i) { 4347 Class<?> t = iterationVariableTypes.get(i); 4348 if (init.get(i) == null) { 4349 init.set(i, empty(methodType(t, commonSuffix))); 4350 } 4351 if (step.get(i) == null) { 4352 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); 4353 } 4354 if (pred.get(i) == null) { 4355 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence)); 4356 } 4357 if (fini.get(i) == null) { 4358 fini.set(i, empty(methodType(t, commonParameterSequence))); 4359 } 4360 } 4361 4362 // Step 4: fill in missing parameter types. 4363 // Also convert all handles to fixed-arity handles. 4364 List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix)); 4365 List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence)); 4366 List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence)); 4367 List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence)); 4368 4369 assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). 4370 allMatch(pl -> pl.equals(commonSuffix)); 4371 assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). 4372 allMatch(pl -> pl.equals(commonParameterSequence)); 4373 4374 // Android-changed: transformer implementation. 4375 // return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); 4376 return new Transformers.Loop(loopReturnType, 4377 commonSuffix, 4378 finit.toArray(MethodHandle[]::new), 4379 fstep.toArray(MethodHandle[]::new), 4380 fpred.toArray(MethodHandle[]::new), 4381 ffini.toArray(MethodHandle[]::new)); 4382 } 4383 loopChecks0(MethodHandle[][] clauses)4384 private static void loopChecks0(MethodHandle[][] clauses) { 4385 if (clauses == null || clauses.length == 0) { 4386 throw newIllegalArgumentException("null or no clauses passed"); 4387 } 4388 if (Stream.of(clauses).anyMatch(Objects::isNull)) { 4389 throw newIllegalArgumentException("null clauses are not allowed"); 4390 } 4391 if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { 4392 throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); 4393 } 4394 } 4395 loopChecks1a(int i, MethodHandle in, MethodHandle st)4396 private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) { 4397 if (in.type().returnType() != st.type().returnType()) { 4398 throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), 4399 st.type().returnType()); 4400 } 4401 } 4402 longestParameterList(Stream<MethodHandle> mhs, int skipSize)4403 private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) { 4404 final List<Class<?>> empty = List.of(); 4405 final List<Class<?>> longest = mhs.filter(Objects::nonNull). 4406 // take only those that can contribute to a common suffix because they are longer than the prefix 4407 map(MethodHandle::type). 4408 filter(t -> t.parameterCount() > skipSize). 4409 map(MethodType::parameterList). 4410 reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 4411 return longest.size() == 0 ? empty : longest.subList(skipSize, longest.size()); 4412 } 4413 longestParameterList(List<List<Class<?>>> lists)4414 private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) { 4415 final List<Class<?>> empty = List.of(); 4416 return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); 4417 } 4418 buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize)4419 private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { 4420 final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize); 4421 final List<Class<?>> longest2 = longestParameterList(init.stream(), 0); 4422 return longestParameterList(Arrays.asList(longest1, longest2)); 4423 } 4424 loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix)4425 private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { 4426 if (init.stream().filter(Objects::nonNull).map(MethodHandle::type). 4427 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) { 4428 throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + 4429 " (common suffix: " + commonSuffix + ")"); 4430 } 4431 } 4432 loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType)4433 private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { 4434 if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4435 anyMatch(t -> t != loopReturnType)) { 4436 throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + 4437 loopReturnType + ")"); 4438 } 4439 4440 if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { 4441 throw newIllegalArgumentException("no predicate found", pred); 4442 } 4443 if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). 4444 anyMatch(t -> t != boolean.class)) { 4445 throw newIllegalArgumentException("predicates must have boolean return type", pred); 4446 } 4447 } 4448 loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence)4449 private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { 4450 if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). 4451 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) { 4452 throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + 4453 "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); 4454 } 4455 } 4456 fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams)4457 private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { 4458 return hs.stream().map(h -> { 4459 int pc = h.type().parameterCount(); 4460 int tpsize = targetParams.size(); 4461 return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h; 4462 }).collect(Collectors.toList()); 4463 } 4464 fixArities(List<MethodHandle> hs)4465 private static List<MethodHandle> fixArities(List<MethodHandle> hs) { 4466 return hs.stream().map(MethodHandle::asFixedArity).collect(Collectors.toList()); 4467 } 4468 4469 /** 4470 * Constructs a {@code while} loop from an initializer, a body, and a predicate. 4471 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4472 * <p> 4473 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 4474 * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate 4475 * evaluates to {@code true}). 4476 * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case). 4477 * <p> 4478 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 4479 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 4480 * and updated with the value returned from its invocation. The result of loop execution will be 4481 * the final value of the additional loop-local variable (if present). 4482 * <p> 4483 * The following rules hold for these argument handles:<ul> 4484 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 4485 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 4486 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 4487 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 4488 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 4489 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 4490 * It will constrain the parameter lists of the other loop parts. 4491 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 4492 * list {@code (A...)} is called the <em>external parameter list</em>. 4493 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 4494 * additional state variable of the loop. 4495 * The body must both accept and return a value of this type {@code V}. 4496 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 4497 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 4498 * <a href="MethodHandles.html#effid">effectively identical</a> 4499 * to the external parameter list {@code (A...)}. 4500 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 4501 * {@linkplain #empty default value}. 4502 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 4503 * Its parameter list (either empty or of the form {@code (V A*)}) must be 4504 * effectively identical to the internal parameter list. 4505 * </ul> 4506 * <p> 4507 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 4508 * <li>The loop handle's result type is the result type {@code V} of the body. 4509 * <li>The loop handle's parameter types are the types {@code (A...)}, 4510 * from the external parameter list. 4511 * </ul> 4512 * <p> 4513 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4514 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4515 * passed to the loop. 4516 * <blockquote><pre>{@code 4517 * V init(A...); 4518 * boolean pred(V, A...); 4519 * V body(V, A...); 4520 * V whileLoop(A... a...) { 4521 * V v = init(a...); 4522 * while (pred(v, a...)) { 4523 * v = body(v, a...); 4524 * } 4525 * return v; 4526 * } 4527 * }</pre></blockquote> 4528 * 4529 * @apiNote Example: 4530 * <blockquote><pre>{@code 4531 * // implement the zip function for lists as a loop handle 4532 * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } 4533 * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } 4534 * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { 4535 * zip.add(a.next()); 4536 * zip.add(b.next()); 4537 * return zip; 4538 * } 4539 * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods 4540 * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); 4541 * List<String> a = Arrays.asList("a", "b", "c", "d"); 4542 * List<String> b = Arrays.asList("e", "f", "g", "h"); 4543 * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); 4544 * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); 4545 * }</pre></blockquote> 4546 * 4547 * 4548 * @apiNote The implementation of this method can be expressed as follows: 4549 * <blockquote><pre>{@code 4550 * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4551 * MethodHandle fini = (body.type().returnType() == void.class 4552 * ? null : identity(body.type().returnType())); 4553 * MethodHandle[] 4554 * checkExit = { null, null, pred, fini }, 4555 * varBody = { init, body }; 4556 * return loop(checkExit, varBody); 4557 * } 4558 * }</pre></blockquote> 4559 * 4560 * @param init optional initializer, providing the initial value of the loop variable. 4561 * May be {@code null}, implying a default initial value. See above for other constraints. 4562 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 4563 * above for other constraints. 4564 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 4565 * See above for other constraints. 4566 * 4567 * @return a method handle implementing the {@code while} loop as described by the arguments. 4568 * @throws IllegalArgumentException if the rules for the arguments are violated. 4569 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 4570 * 4571 * @see #loop(MethodHandle[][]) 4572 * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle) 4573 * @since 9 4574 */ whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body)4575 public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { 4576 whileLoopChecks(init, pred, body); 4577 MethodHandle fini = identityOrVoid(body.type().returnType()); 4578 MethodHandle[] checkExit = { null, null, pred, fini }; 4579 MethodHandle[] varBody = { init, body }; 4580 return loop(checkExit, varBody); 4581 } 4582 4583 /** 4584 * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. 4585 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4586 * <p> 4587 * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this 4588 * method will, in each iteration, first execute its body and then evaluate the predicate. 4589 * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body. 4590 * <p> 4591 * The {@code init} handle describes the initial value of an additional optional loop-local variable. 4592 * In each iteration, this loop-local variable, if present, will be passed to the {@code body} 4593 * and updated with the value returned from its invocation. The result of loop execution will be 4594 * the final value of the additional loop-local variable (if present). 4595 * <p> 4596 * The following rules hold for these argument handles:<ul> 4597 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 4598 * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}. 4599 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 4600 * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V} 4601 * is quietly dropped from the parameter list, leaving {@code (A...)V}.) 4602 * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>. 4603 * It will constrain the parameter lists of the other loop parts. 4604 * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter 4605 * list {@code (A...)} is called the <em>external parameter list</em>. 4606 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 4607 * additional state variable of the loop. 4608 * The body must both accept and return a value of this type {@code V}. 4609 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 4610 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 4611 * <a href="MethodHandles.html#effid">effectively identical</a> 4612 * to the external parameter list {@code (A...)}. 4613 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 4614 * {@linkplain #empty default value}. 4615 * <li>The {@code pred} handle must not be {@code null}. It must have {@code boolean} as its return type. 4616 * Its parameter list (either empty or of the form {@code (V A*)}) must be 4617 * effectively identical to the internal parameter list. 4618 * </ul> 4619 * <p> 4620 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 4621 * <li>The loop handle's result type is the result type {@code V} of the body. 4622 * <li>The loop handle's parameter types are the types {@code (A...)}, 4623 * from the external parameter list. 4624 * </ul> 4625 * <p> 4626 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4627 * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument 4628 * passed to the loop. 4629 * <blockquote><pre>{@code 4630 * V init(A...); 4631 * boolean pred(V, A...); 4632 * V body(V, A...); 4633 * V doWhileLoop(A... a...) { 4634 * V v = init(a...); 4635 * do { 4636 * v = body(v, a...); 4637 * } while (pred(v, a...)); 4638 * return v; 4639 * } 4640 * }</pre></blockquote> 4641 * 4642 * @apiNote Example: 4643 * <blockquote><pre>{@code 4644 * // int i = 0; while (i < limit) { ++i; } return i; => limit 4645 * static int zero(int limit) { return 0; } 4646 * static int step(int i, int limit) { return i + 1; } 4647 * static boolean pred(int i, int limit) { return i < limit; } 4648 * // assume MH_zero, MH_step, and MH_pred are handles to the above methods 4649 * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); 4650 * assertEquals(23, loop.invoke(23)); 4651 * }</pre></blockquote> 4652 * 4653 * 4654 * @apiNote The implementation of this method can be expressed as follows: 4655 * <blockquote><pre>{@code 4656 * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4657 * MethodHandle fini = (body.type().returnType() == void.class 4658 * ? null : identity(body.type().returnType())); 4659 * MethodHandle[] clause = { init, body, pred, fini }; 4660 * return loop(clause); 4661 * } 4662 * }</pre></blockquote> 4663 * 4664 * @param init optional initializer, providing the initial value of the loop variable. 4665 * May be {@code null}, implying a default initial value. See above for other constraints. 4666 * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type. 4667 * See above for other constraints. 4668 * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See 4669 * above for other constraints. 4670 * 4671 * @return a method handle implementing the {@code while} loop as described by the arguments. 4672 * @throws IllegalArgumentException if the rules for the arguments are violated. 4673 * @throws NullPointerException if {@code pred} or {@code body} are {@code null}. 4674 * 4675 * @see #loop(MethodHandle[][]) 4676 * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle) 4677 * @since 9 4678 */ doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred)4679 public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { 4680 whileLoopChecks(init, pred, body); 4681 MethodHandle fini = identityOrVoid(body.type().returnType()); 4682 MethodHandle[] clause = {init, body, pred, fini }; 4683 return loop(clause); 4684 } 4685 whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body)4686 private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) { 4687 Objects.requireNonNull(pred); 4688 Objects.requireNonNull(body); 4689 MethodType bodyType = body.type(); 4690 Class<?> returnType = bodyType.returnType(); 4691 List<Class<?>> innerList = bodyType.parameterList(); 4692 List<Class<?>> outerList = innerList; 4693 if (returnType == void.class) { 4694 // OK 4695 } else if (innerList.size() == 0 || innerList.get(0) != returnType) { 4696 // leading V argument missing => error 4697 MethodType expected = bodyType.insertParameterTypes(0, returnType); 4698 throw misMatchedTypes("body function", bodyType, expected); 4699 } else { 4700 outerList = innerList.subList(1, innerList.size()); 4701 } 4702 MethodType predType = pred.type(); 4703 if (predType.returnType() != boolean.class || 4704 !predType.effectivelyIdenticalParameters(0, innerList)) { 4705 throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList)); 4706 } 4707 if (init != null) { 4708 MethodType initType = init.type(); 4709 if (initType.returnType() != returnType || 4710 !initType.effectivelyIdenticalParameters(0, outerList)) { 4711 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 4712 } 4713 } 4714 } 4715 4716 /** 4717 * Constructs a loop that runs a given number of iterations. 4718 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4719 * <p> 4720 * The number of iterations is determined by the {@code iterations} handle evaluation result. 4721 * The loop counter {@code i} is an extra loop iteration variable of type {@code int}. 4722 * It will be initialized to 0 and incremented by 1 in each iteration. 4723 * <p> 4724 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 4725 * of that type is also present. This variable is initialized using the optional {@code init} handle, 4726 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 4727 * <p> 4728 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 4729 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 4730 * iteration variable. 4731 * The result of the loop handle execution will be the final {@code V} value of that variable 4732 * (or {@code void} if there is no {@code V} variable). 4733 * <p> 4734 * The following rules hold for the argument handles:<ul> 4735 * <li>The {@code iterations} handle must not be {@code null}, and must return 4736 * the type {@code int}, referred to here as {@code I} in parameter type lists. 4737 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 4738 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 4739 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 4740 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 4741 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 4742 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 4743 * of types called the <em>internal parameter list</em>. 4744 * It will constrain the parameter lists of the other loop parts. 4745 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 4746 * with no additional {@code A} types, then the internal parameter list is extended by 4747 * the argument types {@code A...} of the {@code iterations} handle. 4748 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 4749 * list {@code (A...)} is called the <em>external parameter list</em>. 4750 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 4751 * additional state variable of the loop. 4752 * The body must both accept a leading parameter and return a value of this type {@code V}. 4753 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 4754 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 4755 * <a href="MethodHandles.html#effid">effectively identical</a> 4756 * to the external parameter list {@code (A...)}. 4757 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 4758 * {@linkplain #empty default value}. 4759 * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be 4760 * effectively identical to the external parameter list {@code (A...)}. 4761 * </ul> 4762 * <p> 4763 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 4764 * <li>The loop handle's result type is the result type {@code V} of the body. 4765 * <li>The loop handle's parameter types are the types {@code (A...)}, 4766 * from the external parameter list. 4767 * </ul> 4768 * <p> 4769 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4770 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 4771 * arguments passed to the loop. 4772 * <blockquote><pre>{@code 4773 * int iterations(A...); 4774 * V init(A...); 4775 * V body(V, int, A...); 4776 * V countedLoop(A... a...) { 4777 * int end = iterations(a...); 4778 * V v = init(a...); 4779 * for (int i = 0; i < end; ++i) { 4780 * v = body(v, i, a...); 4781 * } 4782 * return v; 4783 * } 4784 * }</pre></blockquote> 4785 * 4786 * @apiNote Example with a fully conformant body method: 4787 * <blockquote><pre>{@code 4788 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 4789 * // => a variation on a well known theme 4790 * static String step(String v, int counter, String init) { return "na " + v; } 4791 * // assume MH_step is a handle to the method above 4792 * MethodHandle fit13 = MethodHandles.constant(int.class, 13); 4793 * MethodHandle start = MethodHandles.identity(String.class); 4794 * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step); 4795 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); 4796 * }</pre></blockquote> 4797 * 4798 * @apiNote Example with the simplest possible body method type, 4799 * and passing the number of iterations to the loop invocation: 4800 * <blockquote><pre>{@code 4801 * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; 4802 * // => a variation on a well known theme 4803 * static String step(String v, int counter ) { return "na " + v; } 4804 * // assume MH_step is a handle to the method above 4805 * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class); 4806 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class); 4807 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i) -> "na " + v 4808 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!")); 4809 * }</pre></blockquote> 4810 * 4811 * @apiNote Example that treats the number of iterations, string to append to, and string to append 4812 * as loop parameters: 4813 * <blockquote><pre>{@code 4814 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 4815 * // => a variation on a well known theme 4816 * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; } 4817 * // assume MH_step is a handle to the method above 4818 * MethodHandle count = MethodHandles.identity(int.class); 4819 * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class); 4820 * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step); // (v, i, _, pre, _) -> pre + " " + v 4821 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!")); 4822 * }</pre></blockquote> 4823 * 4824 * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)} 4825 * to enforce a loop type: 4826 * <blockquote><pre>{@code 4827 * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s; 4828 * // => a variation on a well known theme 4829 * static String step(String v, int counter, String pre) { return pre + " " + v; } 4830 * // assume MH_step is a handle to the method above 4831 * MethodType loopType = methodType(String.class, String.class, int.class, String.class); 4832 * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class), 0, loopType.parameterList(), 1); 4833 * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2); 4834 * MethodHandle body = MethodHandles.dropArgumentsToMatch(MH_step, 2, loopType.parameterList(), 0); 4835 * MethodHandle loop = MethodHandles.countedLoop(count, start, body); // (v, i, pre, _, _) -> pre + " " + v 4836 * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!")); 4837 * }</pre></blockquote> 4838 * 4839 * @apiNote The implementation of this method can be expressed as follows: 4840 * <blockquote><pre>{@code 4841 * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4842 * return countedLoop(empty(iterations.type()), iterations, init, body); 4843 * } 4844 * }</pre></blockquote> 4845 * 4846 * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's 4847 * result type must be {@code int}. See above for other constraints. 4848 * @param init optional initializer, providing the initial value of the loop variable. 4849 * May be {@code null}, implying a default initial value. See above for other constraints. 4850 * @param body body of the loop, which may not be {@code null}. 4851 * It controls the loop parameters and result type in the standard case (see above for details). 4852 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 4853 * and may accept any number of additional types. 4854 * See above for other constraints. 4855 * 4856 * @return a method handle representing the loop. 4857 * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}. 4858 * @throws IllegalArgumentException if any argument violates the rules formulated above. 4859 * 4860 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle) 4861 * @since 9 4862 */ countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body)4863 public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { 4864 return countedLoop(empty(iterations.type()), iterations, init, body); 4865 } 4866 4867 /** 4868 * Constructs a loop that counts over a range of numbers. 4869 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 4870 * <p> 4871 * The loop counter {@code i} is a loop iteration variable of type {@code int}. 4872 * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive) 4873 * values of the loop counter. 4874 * The loop counter will be initialized to the {@code int} value returned from the evaluation of the 4875 * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1. 4876 * <p> 4877 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 4878 * of that type is also present. This variable is initialized using the optional {@code init} handle, 4879 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 4880 * <p> 4881 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 4882 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 4883 * iteration variable. 4884 * The result of the loop handle execution will be the final {@code V} value of that variable 4885 * (or {@code void} if there is no {@code V} variable). 4886 * <p> 4887 * The following rules hold for the argument handles:<ul> 4888 * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return 4889 * the common type {@code int}, referred to here as {@code I} in parameter type lists. 4890 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 4891 * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}. 4892 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 4893 * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V} 4894 * is quietly dropped from the parameter list, leaving {@code (I A...)V}.) 4895 * <li>The parameter list {@code (V I A...)} of the body contributes to a list 4896 * of types called the <em>internal parameter list</em>. 4897 * It will constrain the parameter lists of the other loop parts. 4898 * <li>As a special case, if the body contributes only {@code V} and {@code I} types, 4899 * with no additional {@code A} types, then the internal parameter list is extended by 4900 * the argument types {@code A...} of the {@code end} handle. 4901 * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter 4902 * list {@code (A...)} is called the <em>external parameter list</em>. 4903 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 4904 * additional state variable of the loop. 4905 * The body must both accept a leading parameter and return a value of this type {@code V}. 4906 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 4907 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 4908 * <a href="MethodHandles.html#effid">effectively identical</a> 4909 * to the external parameter list {@code (A...)}. 4910 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 4911 * {@linkplain #empty default value}. 4912 * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be 4913 * effectively identical to the external parameter list {@code (A...)}. 4914 * <li>Likewise, the parameter list of {@code end} must be effectively identical 4915 * to the external parameter list. 4916 * </ul> 4917 * <p> 4918 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 4919 * <li>The loop handle's result type is the result type {@code V} of the body. 4920 * <li>The loop handle's parameter types are the types {@code (A...)}, 4921 * from the external parameter list. 4922 * </ul> 4923 * <p> 4924 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 4925 * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent 4926 * arguments passed to the loop. 4927 * <blockquote><pre>{@code 4928 * int start(A...); 4929 * int end(A...); 4930 * V init(A...); 4931 * V body(V, int, A...); 4932 * V countedLoop(A... a...) { 4933 * int e = end(a...); 4934 * int s = start(a...); 4935 * V v = init(a...); 4936 * for (int i = s; i < e; ++i) { 4937 * v = body(v, i, a...); 4938 * } 4939 * return v; 4940 * } 4941 * }</pre></blockquote> 4942 * 4943 * @apiNote The implementation of this method can be expressed as follows: 4944 * <blockquote><pre>{@code 4945 * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4946 * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); 4947 * // assume MH_increment and MH_predicate are handles to implementation-internal methods with 4948 * // the following semantics: 4949 * // MH_increment: (int limit, int counter) -> counter + 1 4950 * // MH_predicate: (int limit, int counter) -> counter < limit 4951 * Class<?> counterType = start.type().returnType(); // int 4952 * Class<?> returnType = body.type().returnType(); 4953 * MethodHandle incr = MH_increment, pred = MH_predicate, retv = null; 4954 * if (returnType != void.class) { // ignore the V variable 4955 * incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 4956 * pred = dropArguments(pred, 1, returnType); // ditto 4957 * retv = dropArguments(identity(returnType), 0, counterType); // ignore limit 4958 * } 4959 * body = dropArguments(body, 0, counterType); // ignore the limit variable 4960 * MethodHandle[] 4961 * loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 4962 * bodyClause = { init, body }, // v = init(); v = body(v, i) 4963 * indexVar = { start, incr }; // i = start(); i = i + 1 4964 * return loop(loopLimit, bodyClause, indexVar); 4965 * } 4966 * }</pre></blockquote> 4967 * 4968 * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}. 4969 * See above for other constraints. 4970 * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to 4971 * {@code end-1}). The result type must be {@code int}. See above for other constraints. 4972 * @param init optional initializer, providing the initial value of the loop variable. 4973 * May be {@code null}, implying a default initial value. See above for other constraints. 4974 * @param body body of the loop, which may not be {@code null}. 4975 * It controls the loop parameters and result type in the standard case (see above for details). 4976 * It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter), 4977 * and may accept any number of additional types. 4978 * See above for other constraints. 4979 * 4980 * @return a method handle representing the loop. 4981 * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}. 4982 * @throws IllegalArgumentException if any argument violates the rules formulated above. 4983 * 4984 * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle) 4985 * @since 9 4986 */ countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body)4987 public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 4988 countedLoopChecks(start, end, init, body); 4989 Class<?> counterType = start.type().returnType(); // int, but who's counting? 4990 Class<?> limitType = end.type().returnType(); // yes, int again 4991 Class<?> returnType = body.type().returnType(); 4992 // Android-changed: getConstantHandle is in MethodHandles. 4993 // MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep); 4994 // MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred); 4995 MethodHandle incr = getConstantHandle(MH_countedLoopStep); 4996 MethodHandle pred = getConstantHandle(MH_countedLoopPred); 4997 MethodHandle retv = null; 4998 if (returnType != void.class) { 4999 incr = dropArguments(incr, 1, returnType); // (limit, v, i) => (limit, i) 5000 pred = dropArguments(pred, 1, returnType); // ditto 5001 retv = dropArguments(identity(returnType), 0, counterType); 5002 } 5003 body = dropArguments(body, 0, counterType); // ignore the limit variable 5004 MethodHandle[] 5005 loopLimit = { end, null, pred, retv }, // limit = end(); i < limit || return v 5006 bodyClause = { init, body }, // v = init(); v = body(v, i) 5007 indexVar = { start, incr }; // i = start(); i = i + 1 5008 return loop(loopLimit, bodyClause, indexVar); 5009 } 5010 countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body)5011 private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { 5012 Objects.requireNonNull(start); 5013 Objects.requireNonNull(end); 5014 Objects.requireNonNull(body); 5015 Class<?> counterType = start.type().returnType(); 5016 if (counterType != int.class) { 5017 MethodType expected = start.type().changeReturnType(int.class); 5018 throw misMatchedTypes("start function", start.type(), expected); 5019 } else if (end.type().returnType() != counterType) { 5020 MethodType expected = end.type().changeReturnType(counterType); 5021 throw misMatchedTypes("end function", end.type(), expected); 5022 } 5023 MethodType bodyType = body.type(); 5024 Class<?> returnType = bodyType.returnType(); 5025 List<Class<?>> innerList = bodyType.parameterList(); 5026 // strip leading V value if present 5027 int vsize = (returnType == void.class ? 0 : 1); 5028 if (vsize != 0 && (innerList.size() == 0 || innerList.get(0) != returnType)) { 5029 // argument list has no "V" => error 5030 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5031 throw misMatchedTypes("body function", bodyType, expected); 5032 } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) { 5033 // missing I type => error 5034 MethodType expected = bodyType.insertParameterTypes(vsize, counterType); 5035 throw misMatchedTypes("body function", bodyType, expected); 5036 } 5037 List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size()); 5038 if (outerList.isEmpty()) { 5039 // special case; take lists from end handle 5040 outerList = end.type().parameterList(); 5041 innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList(); 5042 } 5043 MethodType expected = methodType(counterType, outerList); 5044 if (!start.type().effectivelyIdenticalParameters(0, outerList)) { 5045 throw misMatchedTypes("start parameter types", start.type(), expected); 5046 } 5047 if (end.type() != start.type() && 5048 !end.type().effectivelyIdenticalParameters(0, outerList)) { 5049 throw misMatchedTypes("end parameter types", end.type(), expected); 5050 } 5051 if (init != null) { 5052 MethodType initType = init.type(); 5053 if (initType.returnType() != returnType || 5054 !initType.effectivelyIdenticalParameters(0, outerList)) { 5055 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList)); 5056 } 5057 } 5058 } 5059 5060 /** 5061 * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}. 5062 * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. 5063 * <p> 5064 * The iterator itself will be determined by the evaluation of the {@code iterator} handle. 5065 * Each value it produces will be stored in a loop iteration variable of type {@code T}. 5066 * <p> 5067 * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable 5068 * of that type is also present. This variable is initialized using the optional {@code init} handle, 5069 * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}. 5070 * <p> 5071 * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle. 5072 * A non-{@code void} value returned from the body (of type {@code V}) updates the leading 5073 * iteration variable. 5074 * The result of the loop handle execution will be the final {@code V} value of that variable 5075 * (or {@code void} if there is no {@code V} variable). 5076 * <p> 5077 * The following rules hold for the argument handles:<ul> 5078 * <li>The {@code body} handle must not be {@code null}; its type must be of the form 5079 * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}. 5080 * (In the {@code void} case, we assign the type {@code void} to the name {@code V}, 5081 * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V} 5082 * is quietly dropped from the parameter list, leaving {@code (T A...)V}.) 5083 * <li>The parameter list {@code (V T A...)} of the body contributes to a list 5084 * of types called the <em>internal parameter list</em>. 5085 * It will constrain the parameter lists of the other loop parts. 5086 * <li>As a special case, if the body contributes only {@code V} and {@code T} types, 5087 * with no additional {@code A} types, then the internal parameter list is extended by 5088 * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the 5089 * single type {@code Iterable} is added and constitutes the {@code A...} list. 5090 * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter 5091 * list {@code (A...)} is called the <em>external parameter list</em>. 5092 * <li>The body return type {@code V}, if non-{@code void}, determines the type of an 5093 * additional state variable of the loop. 5094 * The body must both accept a leading parameter and return a value of this type {@code V}. 5095 * <li>If {@code init} is non-{@code null}, it must have return type {@code V}. 5096 * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be 5097 * <a href="MethodHandles.html#effid">effectively identical</a> 5098 * to the external parameter list {@code (A...)}. 5099 * <li>If {@code init} is {@code null}, the loop variable will be initialized to its 5100 * {@linkplain #empty default value}. 5101 * <li>If the {@code iterator} handle is non-{@code null}, it must have the return 5102 * type {@code java.util.Iterator} or a subtype thereof. 5103 * The iterator it produces when the loop is executed will be assumed 5104 * to yield values which can be converted to type {@code T}. 5105 * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be 5106 * effectively identical to the external parameter list {@code (A...)}. 5107 * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves 5108 * like {@link java.lang.Iterable#iterator()}. In that case, the internal parameter list 5109 * {@code (V T A...)} must have at least one {@code A} type, and the default iterator 5110 * handle parameter is adjusted to accept the leading {@code A} type, as if by 5111 * the {@link MethodHandle#asType asType} conversion method. 5112 * The leading {@code A} type must be {@code Iterable} or a subtype thereof. 5113 * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}. 5114 * </ul> 5115 * <p> 5116 * The type {@code T} may be either a primitive or reference. 5117 * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator}, 5118 * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object} 5119 * as if by the {@link MethodHandle#asType asType} conversion method. 5120 * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur 5121 * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}. 5122 * <p> 5123 * The resulting loop handle's result type and parameter signature are determined as follows:<ul> 5124 * <li>The loop handle's result type is the result type {@code V} of the body. 5125 * <li>The loop handle's parameter types are the types {@code (A...)}, 5126 * from the external parameter list. 5127 * </ul> 5128 * <p> 5129 * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of 5130 * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the 5131 * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop. 5132 * <blockquote><pre>{@code 5133 * Iterator<T> iterator(A...); // defaults to Iterable::iterator 5134 * V init(A...); 5135 * V body(V,T,A...); 5136 * V iteratedLoop(A... a...) { 5137 * Iterator<T> it = iterator(a...); 5138 * V v = init(a...); 5139 * while (it.hasNext()) { 5140 * T t = it.next(); 5141 * v = body(v, t, a...); 5142 * } 5143 * return v; 5144 * } 5145 * }</pre></blockquote> 5146 * 5147 * @apiNote Example: 5148 * <blockquote><pre>{@code 5149 * // get an iterator from a list 5150 * static List<String> reverseStep(List<String> r, String e) { 5151 * r.add(0, e); 5152 * return r; 5153 * } 5154 * static List<String> newArrayList() { return new ArrayList<>(); } 5155 * // assume MH_reverseStep and MH_newArrayList are handles to the above methods 5156 * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); 5157 * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); 5158 * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); 5159 * assertEquals(reversedList, (List<String>) loop.invoke(list)); 5160 * }</pre></blockquote> 5161 * 5162 * @apiNote The implementation of this method can be expressed approximately as follows: 5163 * <blockquote><pre>{@code 5164 * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5165 * // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable 5166 * Class<?> returnType = body.type().returnType(); 5167 * Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 5168 * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); 5169 * MethodHandle retv = null, step = body, startIter = iterator; 5170 * if (returnType != void.class) { 5171 * // the simple thing first: in (I V A...), drop the I to get V 5172 * retv = dropArguments(identity(returnType), 0, Iterator.class); 5173 * // body type signature (V T A...), internal loop types (I V A...) 5174 * step = swapArguments(body, 0, 1); // swap V <-> T 5175 * } 5176 * if (startIter == null) startIter = MH_getIter; 5177 * MethodHandle[] 5178 * iterVar = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext()) 5179 * bodyClause = { init, filterArguments(step, 0, nextVal) }; // v = body(v, t, a) 5180 * return loop(iterVar, bodyClause); 5181 * } 5182 * }</pre></blockquote> 5183 * 5184 * @param iterator an optional handle to return the iterator to start the loop. 5185 * If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype. 5186 * See above for other constraints. 5187 * @param init optional initializer, providing the initial value of the loop variable. 5188 * May be {@code null}, implying a default initial value. See above for other constraints. 5189 * @param body body of the loop, which may not be {@code null}. 5190 * It controls the loop parameters and result type in the standard case (see above for details). 5191 * It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values), 5192 * and may accept any number of additional types. 5193 * See above for other constraints. 5194 * 5195 * @return a method handle embodying the iteration loop functionality. 5196 * @throws NullPointerException if the {@code body} handle is {@code null}. 5197 * @throws IllegalArgumentException if any argument violates the above requirements. 5198 * 5199 * @since 9 5200 */ iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body)5201 public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5202 Class<?> iterableType = iteratedLoopChecks(iterator, init, body); 5203 Class<?> returnType = body.type().returnType(); 5204 // Android-changed: getConstantHandle is in MethodHandles. 5205 // MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred); 5206 // MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); 5207 MethodHandle hasNext = getConstantHandle(MH_iteratePred); 5208 MethodHandle nextRaw = getConstantHandle(MH_iterateNext); 5209 MethodHandle startIter; 5210 MethodHandle nextVal; 5211 { 5212 MethodType iteratorType; 5213 if (iterator == null) { 5214 // derive argument type from body, if available, else use Iterable 5215 // Android-changed: getConstantHandle is in MethodHandles. 5216 // startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); 5217 startIter = getConstantHandle(MH_initIterator); 5218 iteratorType = startIter.type().changeParameterType(0, iterableType); 5219 } else { 5220 // force return type to the internal iterator class 5221 iteratorType = iterator.type().changeReturnType(Iterator.class); 5222 startIter = iterator; 5223 } 5224 Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1); 5225 MethodType nextValType = nextRaw.type().changeReturnType(ttype); 5226 5227 // perform the asType transforms under an exception transformer, as per spec.: 5228 try { 5229 startIter = startIter.asType(iteratorType); 5230 nextVal = nextRaw.asType(nextValType); 5231 } catch (WrongMethodTypeException ex) { 5232 throw new IllegalArgumentException(ex); 5233 } 5234 } 5235 5236 MethodHandle retv = null, step = body; 5237 if (returnType != void.class) { 5238 // the simple thing first: in (I V A...), drop the I to get V 5239 retv = dropArguments(identity(returnType), 0, Iterator.class); 5240 // body type signature (V T A...), internal loop types (I V A...) 5241 step = swapArguments(body, 0, 1); // swap V <-> T 5242 } 5243 5244 MethodHandle[] 5245 iterVar = { startIter, null, hasNext, retv }, 5246 bodyClause = { init, filterArgument(step, 0, nextVal) }; 5247 return loop(iterVar, bodyClause); 5248 } 5249 iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body)5250 private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) { 5251 Objects.requireNonNull(body); 5252 MethodType bodyType = body.type(); 5253 Class<?> returnType = bodyType.returnType(); 5254 List<Class<?>> internalParamList = bodyType.parameterList(); 5255 // strip leading V value if present 5256 int vsize = (returnType == void.class ? 0 : 1); 5257 if (vsize != 0 && (internalParamList.size() == 0 || internalParamList.get(0) != returnType)) { 5258 // argument list has no "V" => error 5259 MethodType expected = bodyType.insertParameterTypes(0, returnType); 5260 throw misMatchedTypes("body function", bodyType, expected); 5261 } else if (internalParamList.size() <= vsize) { 5262 // missing T type => error 5263 MethodType expected = bodyType.insertParameterTypes(vsize, Object.class); 5264 throw misMatchedTypes("body function", bodyType, expected); 5265 } 5266 List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size()); 5267 Class<?> iterableType = null; 5268 if (iterator != null) { 5269 // special case; if the body handle only declares V and T then 5270 // the external parameter list is obtained from iterator handle 5271 if (externalParamList.isEmpty()) { 5272 externalParamList = iterator.type().parameterList(); 5273 } 5274 MethodType itype = iterator.type(); 5275 if (!Iterator.class.isAssignableFrom(itype.returnType())) { 5276 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); 5277 } 5278 if (!itype.effectivelyIdenticalParameters(0, externalParamList)) { 5279 MethodType expected = methodType(itype.returnType(), externalParamList); 5280 throw misMatchedTypes("iterator parameters", itype, expected); 5281 } 5282 } else { 5283 if (externalParamList.isEmpty()) { 5284 // special case; if the iterator handle is null and the body handle 5285 // only declares V and T then the external parameter list consists 5286 // of Iterable 5287 externalParamList = Arrays.asList(Iterable.class); 5288 iterableType = Iterable.class; 5289 } else { 5290 // special case; if the iterator handle is null and the external 5291 // parameter list is not empty then the first parameter must be 5292 // assignable to Iterable 5293 iterableType = externalParamList.get(0); 5294 if (!Iterable.class.isAssignableFrom(iterableType)) { 5295 throw newIllegalArgumentException( 5296 "inferred first loop argument must inherit from Iterable: " + iterableType); 5297 } 5298 } 5299 } 5300 if (init != null) { 5301 MethodType initType = init.type(); 5302 if (initType.returnType() != returnType || 5303 !initType.effectivelyIdenticalParameters(0, externalParamList)) { 5304 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList)); 5305 } 5306 } 5307 return iterableType; // help the caller a bit 5308 } 5309 swapArguments(MethodHandle mh, int i, int j)5310 /*non-public*/ static MethodHandle swapArguments(MethodHandle mh, int i, int j) { 5311 // there should be a better way to uncross my wires 5312 int arity = mh.type().parameterCount(); 5313 int[] order = new int[arity]; 5314 for (int k = 0; k < arity; k++) order[k] = k; 5315 order[i] = j; order[j] = i; 5316 Class<?>[] types = mh.type().parameterArray(); 5317 Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti; 5318 MethodType swapType = methodType(mh.type().returnType(), types); 5319 return permuteArguments(mh, swapType, order); 5320 } 5321 5322 /** 5323 * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. 5324 * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception 5325 * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The 5326 * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The 5327 * value returned from the {@code cleanup} handle's execution will be the result of the execution of the 5328 * {@code try-finally} handle. 5329 * <p> 5330 * The {@code cleanup} handle will be passed one or two additional leading arguments. 5331 * The first is the exception thrown during the 5332 * execution of the {@code target} handle, or {@code null} if no exception was thrown. 5333 * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, 5334 * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. 5335 * The second argument is not present if the {@code target} handle has a {@code void} return type. 5336 * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists 5337 * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) 5338 * <p> 5339 * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except 5340 * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or 5341 * two extra leading parameters:<ul> 5342 * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and 5343 * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry 5344 * the result from the execution of the {@code target} handle. 5345 * This parameter is not present if the {@code target} returns {@code void}. 5346 * </ul> 5347 * <p> 5348 * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of 5349 * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting 5350 * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by 5351 * the cleanup. 5352 * <blockquote><pre>{@code 5353 * V target(A..., B...); 5354 * V cleanup(Throwable, V, A...); 5355 * V adapter(A... a, B... b) { 5356 * V result = (zero value for V); 5357 * Throwable throwable = null; 5358 * try { 5359 * result = target(a..., b...); 5360 * } catch (Throwable t) { 5361 * throwable = t; 5362 * throw t; 5363 * } finally { 5364 * result = cleanup(throwable, result, a...); 5365 * } 5366 * return result; 5367 * } 5368 * }</pre></blockquote> 5369 * <p> 5370 * Note that the saved arguments ({@code a...} in the pseudocode) cannot 5371 * be modified by execution of the target, and so are passed unchanged 5372 * from the caller to the cleanup, if it is invoked. 5373 * <p> 5374 * The target and cleanup must return the same type, even if the cleanup 5375 * always throws. 5376 * To create such a throwing cleanup, compose the cleanup logic 5377 * with {@link #throwException throwException}, 5378 * in order to create a method handle of the correct return type. 5379 * <p> 5380 * Note that {@code tryFinally} never converts exceptions into normal returns. 5381 * In rare cases where exceptions must be converted in that way, first wrap 5382 * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} 5383 * to capture an outgoing exception, and then wrap with {@code tryFinally}. 5384 * <p> 5385 * It is recommended that the first parameter type of {@code cleanup} be 5386 * declared {@code Throwable} rather than a narrower subtype. This ensures 5387 * {@code cleanup} will always be invoked with whatever exception that 5388 * {@code target} throws. Declaring a narrower type may result in a 5389 * {@code ClassCastException} being thrown by the {@code try-finally} 5390 * handle if the type of the exception thrown by {@code target} is not 5391 * assignable to the first parameter type of {@code cleanup}. Note that 5392 * various exception types of {@code VirtualMachineError}, 5393 * {@code LinkageError}, and {@code RuntimeException} can in principle be 5394 * thrown by almost any kind of Java code, and a finally clause that 5395 * catches (say) only {@code IOException} would mask any of the others 5396 * behind a {@code ClassCastException}. 5397 * 5398 * @param target the handle whose execution is to be wrapped in a {@code try} block. 5399 * @param cleanup the handle that is invoked in the finally block. 5400 * 5401 * @return a method handle embodying the {@code try-finally} block composed of the two arguments. 5402 * @throws NullPointerException if any argument is null 5403 * @throws IllegalArgumentException if {@code cleanup} does not accept 5404 * the required leading arguments, or if the method handle types do 5405 * not match in their return types and their 5406 * corresponding trailing parameters 5407 * 5408 * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) 5409 * @since 9 5410 */ tryFinally(MethodHandle target, MethodHandle cleanup)5411 public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { 5412 List<Class<?>> targetParamTypes = target.type().parameterList(); 5413 Class<?> rtype = target.type().returnType(); 5414 5415 tryFinallyChecks(target, cleanup); 5416 5417 // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. 5418 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 5419 // target parameter list. 5420 cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); 5421 5422 // Ensure that the intrinsic type checks the instance thrown by the 5423 // target against the first parameter of cleanup 5424 cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class)); 5425 5426 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 5427 // Android-changed: use Transformer implementation. 5428 // return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes); 5429 return new Transformers.TryFinally(target.asFixedArity(), cleanup.asFixedArity()); 5430 } 5431 tryFinallyChecks(MethodHandle target, MethodHandle cleanup)5432 private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) { 5433 Class<?> rtype = target.type().returnType(); 5434 if (rtype != cleanup.type().returnType()) { 5435 throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); 5436 } 5437 MethodType cleanupType = cleanup.type(); 5438 if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) { 5439 throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); 5440 } 5441 if (rtype != void.class && cleanupType.parameterType(1) != rtype) { 5442 throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); 5443 } 5444 // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the 5445 // target parameter list. 5446 int cleanupArgIndex = rtype == void.class ? 1 : 2; 5447 if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) { 5448 throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", 5449 cleanup.type(), target.type()); 5450 } 5451 } 5452 5453 // BEGIN Android-added: Code from OpenJDK's MethodHandleImpl. 5454 5455 /** 5456 * This method is bound as the predicate in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle, 5457 * MethodHandle) counting loops}. 5458 * 5459 * @param limit the upper bound of the parameter, statically bound at loop creation time. 5460 * @param counter the counter parameter, passed in during loop execution. 5461 * 5462 * @return whether the counter has reached the limit. 5463 * @hide 5464 */ countedLoopPredicate(int limit, int counter)5465 public static boolean countedLoopPredicate(int limit, int counter) { 5466 return counter < limit; 5467 } 5468 5469 /** 5470 * This method is bound as the step function in {@linkplain MethodHandles#countedLoop(MethodHandle, MethodHandle, 5471 * MethodHandle) counting loops} to increment the counter. 5472 * 5473 * @param limit the upper bound of the loop counter (ignored). 5474 * @param counter the loop counter. 5475 * 5476 * @return the loop counter incremented by 1. 5477 * @hide 5478 */ countedLoopStep(int limit, int counter)5479 public static int countedLoopStep(int limit, int counter) { 5480 return counter + 1; 5481 } 5482 5483 /** 5484 * This is bound to initialize the loop-local iterator in {@linkplain MethodHandles#iteratedLoop iterating loops}. 5485 * 5486 * @param it the {@link Iterable} over which the loop iterates. 5487 * 5488 * @return an {@link Iterator} over the argument's elements. 5489 * @hide 5490 */ initIterator(Iterable<?> it)5491 public static Iterator<?> initIterator(Iterable<?> it) { 5492 return it.iterator(); 5493 } 5494 5495 /** 5496 * This method is bound as the predicate in {@linkplain MethodHandles#iteratedLoop iterating loops}. 5497 * 5498 * @param it the iterator to be checked. 5499 * 5500 * @return {@code true} iff there are more elements to iterate over. 5501 * @hide 5502 */ iteratePredicate(Iterator<?> it)5503 public static boolean iteratePredicate(Iterator<?> it) { 5504 return it.hasNext(); 5505 } 5506 5507 /** 5508 * This method is bound as the step for retrieving the current value from the iterator in {@linkplain 5509 * MethodHandles#iteratedLoop iterating loops}. 5510 * 5511 * @param it the iterator. 5512 * 5513 * @return the next element from the iterator. 5514 * @hide 5515 */ iterateNext(Iterator<?> it)5516 public static Object iterateNext(Iterator<?> it) { 5517 return it.next(); 5518 } 5519 5520 // Indexes into constant method handles: 5521 static final int 5522 MH_cast = 0, 5523 MH_selectAlternative = 1, 5524 MH_copyAsPrimitiveArray = 2, 5525 MH_fillNewTypedArray = 3, 5526 MH_fillNewArray = 4, 5527 MH_arrayIdentity = 5, 5528 MH_countedLoopPred = 6, 5529 MH_countedLoopStep = 7, 5530 MH_initIterator = 8, 5531 MH_iteratePred = 9, 5532 MH_iterateNext = 10, 5533 MH_Array_newInstance = 11, 5534 MH_LIMIT = 12; 5535 getConstantHandle(int idx)5536 static MethodHandle getConstantHandle(int idx) { 5537 MethodHandle handle = HANDLES[idx]; 5538 if (handle != null) { 5539 return handle; 5540 } 5541 return setCachedHandle(idx, makeConstantHandle(idx)); 5542 } 5543 setCachedHandle(int idx, final MethodHandle method)5544 private static synchronized MethodHandle setCachedHandle(int idx, final MethodHandle method) { 5545 // Simulate a CAS, to avoid racy duplication of results. 5546 MethodHandle prev = HANDLES[idx]; 5547 if (prev != null) { 5548 return prev; 5549 } 5550 HANDLES[idx] = method; 5551 return method; 5552 } 5553 5554 // Local constant method handles: 5555 private static final @Stable MethodHandle[] HANDLES = new MethodHandle[MH_LIMIT]; 5556 makeConstantHandle(int idx)5557 private static MethodHandle makeConstantHandle(int idx) { 5558 try { 5559 // Android-added: local IMPL_LOOKUP. 5560 final Lookup IMPL_LOOKUP = MethodHandles.Lookup.IMPL_LOOKUP; 5561 switch (idx) { 5562 // Android-removed: not-used. 5563 /* 5564 case MH_cast: 5565 return IMPL_LOOKUP.findVirtual(Class.class, "cast", 5566 MethodType.methodType(Object.class, Object.class)); 5567 case MH_copyAsPrimitiveArray: 5568 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "copyAsPrimitiveArray", 5569 MethodType.methodType(Object.class, Wrapper.class, Object[].class)); 5570 case MH_arrayIdentity: 5571 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "identity", 5572 MethodType.methodType(Object[].class, Object[].class)); 5573 case MH_fillNewArray: 5574 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "fillNewArray", 5575 MethodType.methodType(Object[].class, Integer.class, Object[].class)); 5576 case MH_fillNewTypedArray: 5577 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "fillNewTypedArray", 5578 MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class)); 5579 case MH_selectAlternative: 5580 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "selectAlternative", 5581 MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class)); 5582 */ 5583 case MH_countedLoopPred: 5584 // Android-changed: methods moved to this file. 5585 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopPredicate", 5586 // MethodType.methodType(boolean.class, int.class, int.class)); 5587 return IMPL_LOOKUP.findStatic(MethodHandles.class, "countedLoopPredicate", 5588 MethodType.methodType(boolean.class, int.class, int.class)); 5589 case MH_countedLoopStep: 5590 // Android-changed: methods moved to this file. 5591 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "countedLoopStep", 5592 // MethodType.methodType(int.class, int.class, int.class)); 5593 return IMPL_LOOKUP.findStatic(MethodHandles.class, "countedLoopStep", 5594 MethodType.methodType(int.class, int.class, int.class)); 5595 case MH_initIterator: 5596 // Android-changed: methods moved to this file. 5597 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "initIterator", 5598 // MethodType.methodType(Iterator.class, Iterable.class)); 5599 return IMPL_LOOKUP.findStatic(MethodHandles.class, "initIterator", 5600 MethodType.methodType(Iterator.class, Iterable.class)); 5601 case MH_iteratePred: 5602 // Android-changed: methods moved to this file. 5603 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iteratePredicate", 5604 // MethodType.methodType(boolean.class, Iterator.class)); 5605 return IMPL_LOOKUP.findStatic(MethodHandles.class, "iteratePredicate", 5606 MethodType.methodType(boolean.class, Iterator.class)); 5607 case MH_iterateNext: 5608 // Android-changed: methods moved to this file. 5609 // return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "iterateNext", 5610 // MethodType.methodType(Object.class, Iterator.class)); 5611 return IMPL_LOOKUP.findStatic(MethodHandles.class, "iterateNext", 5612 MethodType.methodType(Object.class, Iterator.class)); 5613 // Android-removed: not-used. 5614 /* 5615 case MH_Array_newInstance: 5616 return IMPL_LOOKUP.findStatic(Array.class, "newInstance", 5617 MethodType.methodType(Object.class, Class.class, int.class)); 5618 */ 5619 } 5620 } catch (ReflectiveOperationException ex) { 5621 throw newInternalError(ex); 5622 } 5623 5624 throw newInternalError("Unknown function index: " + idx); 5625 } 5626 // END Android-added: Code from OpenJDK's MethodHandleImpl. 5627 } 5628