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