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