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