1 /*
   2  * Copyright (c) 2008, 2022, 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 jdk.internal.access.SharedSecrets;
  29 import jdk.internal.misc.Unsafe;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.CallerSensitiveAdapter;
  36 import jdk.internal.reflect.Reflection;
  37 import jdk.internal.vm.annotation.ForceInline;
  38 import sun.invoke.util.ValueConversions;
  39 import sun.invoke.util.VerifyAccess;
  40 import sun.invoke.util.Wrapper;
  41 import sun.reflect.misc.ReflectUtil;
  42 import sun.security.util.SecurityConstants;
  43 
  44 import java.lang.constant.ConstantDescs;
  45 import java.lang.invoke.LambdaForm.BasicType;
  46 import java.lang.reflect.Constructor;
  47 import java.lang.reflect.Field;
  48 import java.lang.reflect.Member;
  49 import java.lang.reflect.Method;
  50 import java.lang.reflect.Modifier;
  51 import java.nio.ByteOrder;
  52 import java.security.ProtectionDomain;
  53 import java.util.ArrayList;
  54 import java.util.Arrays;
  55 import java.util.BitSet;
  56 import java.util.Iterator;
  57 import java.util.List;
  58 import java.util.Objects;
  59 import java.util.Set;
  60 import java.util.concurrent.ConcurrentHashMap;
  61 import java.util.stream.Stream;
  62 
  63 import static java.lang.invoke.LambdaForm.BasicType.V_TYPE;
  64 import static java.lang.invoke.MethodHandleImpl.Intrinsic;
  65 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  66 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  67 import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException;
  68 import static java.lang.invoke.MethodHandleStatics.newInternalError;
  69 import static java.lang.invoke.MethodType.methodType;
  70 
  71 /**
  72  * This class consists exclusively of static methods that operate on or return
  73  * method handles. They fall into several categories:
  74  * <ul>
  75  * <li>Lookup methods which help create method handles for methods and fields.
  76  * <li>Combinator methods, which combine or transform pre-existing method handles into new ones.
  77  * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns.
  78  * </ul>
  79  * A lookup, combinator, or factory method will fail and throw an
  80  * {@code IllegalArgumentException} if the created method handle's type
  81  * would have <a href="MethodHandle.html#maxarity">too many parameters</a>.
  82  *
  83  * @author John Rose, JSR 292 EG
  84  * @since 1.7
  85  */
  86 public class MethodHandles {
  87 
  88     private MethodHandles() { }  // do not instantiate
  89 
  90     static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  91 
  92     // See IMPL_LOOKUP below.
  93 
  94     //// Method handle creation from ordinary methods.
  95 
  96     /**
  97      * Returns a {@link Lookup lookup object} with
  98      * full capabilities to emulate all supported bytecode behaviors of the caller.
  99      * These capabilities include {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access} to the caller.
 100      * Factory methods on the lookup object can create
 101      * <a href="MethodHandleInfo.html#directmh">direct method handles</a>
 102      * for any member that the caller has access to via bytecodes,
 103      * including protected and private fields and methods.
 104      * This lookup object is created by the original lookup class
 105      * and has the {@link Lookup#ORIGINAL ORIGINAL} bit set.
 106      * This lookup object is a <em>capability</em> which may be delegated to trusted agents.
 107      * Do not store it in place where untrusted code can access it.
 108      * <p>
 109      * This method is caller sensitive, which means that it may return different
 110      * values to different callers.
 111      * In cases where {@code MethodHandles.lookup} is called from a context where
 112      * there is no caller frame on the stack (e.g. when called directly
 113      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
 114      * To obtain a {@link Lookup lookup object} in such a context, use an auxiliary class that will
 115      * implicitly be identified as the caller, or use {@link MethodHandles#publicLookup()}
 116      * to obtain a low-privileged lookup instead.
 117      * @return a lookup object for the caller of this method, with
 118      * {@linkplain Lookup#ORIGINAL original} and
 119      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}.
 120      * @throws IllegalCallerException if there is no caller frame on the stack.
 121      */
 122     @CallerSensitive
 123     @ForceInline // to ensure Reflection.getCallerClass optimization
 124     public static Lookup lookup() {
 125         final Class<?> c = Reflection.getCallerClass();
 126         if (c == null) {
 127             throw new IllegalCallerException("no caller frame");
 128         }
 129         return new Lookup(c);
 130     }
 131 
 132     /**
 133      * This lookup method is the alternate implementation of
 134      * the lookup method with a leading caller class argument which is
 135      * non-caller-sensitive.  This method is only invoked by reflection
 136      * and method handle.
 137      */
 138     @CallerSensitiveAdapter
 139     private static Lookup lookup(Class<?> caller) {
 140         if (caller.getClassLoader() == null) {
 141             throw newInternalError("calling lookup() reflectively is not supported: "+caller);
 142         }
 143         return new Lookup(caller);
 144     }
 145 
 146     /**
 147      * Returns a {@link Lookup lookup object} which is trusted minimally.
 148      * The lookup has the {@code UNCONDITIONAL} mode.
 149      * It can only be used to create method handles to public members of
 150      * public classes in packages that are exported unconditionally.
 151      * <p>
 152      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 153      * of this lookup object will be {@link java.lang.Object}.
 154      *
 155      * @apiNote The use of Object is conventional, and because the lookup modes are
 156      * limited, there is no special access provided to the internals of Object, its package
 157      * or its module.  This public lookup object or other lookup object with
 158      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 159      * is not used to determine the lookup context.
 160      *
 161      * <p style="font-size:smaller;">
 162      * <em>Discussion:</em>
 163      * The lookup class can be changed to any other class {@code C} using an expression of the form
 164      * {@link Lookup#in publicLookup().in(C.class)}.
 165      * A public lookup object is always subject to
 166      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 167      * Also, it cannot access
 168      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 169      * @return a lookup object which is trusted minimally
 170      *
 171      * @revised 9
 172      */
 173     public static Lookup publicLookup() {
 174         return Lookup.PUBLIC_LOOKUP;
 175     }
 176 
 177     /**
 178      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 179      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">private access</a>.
 180      * The returned lookup object can provide access to classes in modules and packages,
 181      * and members of those classes, outside the normal rules of Java access control,
 182      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 183      * <p>
 184      * A caller, specified as a {@code Lookup} object, in module {@code M1} is
 185      * allowed to do deep reflection on module {@code M2} and package of the target class
 186      * if and only if all of the following conditions are {@code true}:
 187      * <ul>
 188      * <li>If there is a security manager, its {@code checkPermission} method is
 189      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 190      * that must return normally.
 191      * <li>The caller lookup object must have {@linkplain Lookup#hasFullPrivilegeAccess()
 192      * full privilege access}.  Specifically:
 193      *   <ul>
 194      *     <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 195      *         (This is because otherwise there would be no way to ensure the original lookup
 196      *         creator was a member of any particular module, and so any subsequent checks
 197      *         for readability and qualified exports would become ineffective.)
 198      *     <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 199      *         (This is because an application intending to share intra-module access
 200      *         using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 201      *         deep reflection to its own module.)
 202      *   </ul>
 203      * <li>The target class must be a proper class, not a primitive or array class.
 204      * (Thus, {@code M2} is well-defined.)
 205      * <li>If the caller module {@code M1} differs from
 206      * the target module {@code M2} then both of the following must be true:
 207      *   <ul>
 208      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 209      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 210      *         containing the target class to at least {@code M1}.</li>
 211      *   </ul>
 212      * </ul>
 213      * <p>
 214      * If any of the above checks is violated, this method fails with an
 215      * exception.
 216      * <p>
 217      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 218      * returns a {@code Lookup} on {@code targetClass} with
 219      * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege access}
 220      * with {@code null} previous lookup class.
 221      * <p>
 222      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 223      * returns a {@code Lookup} on {@code targetClass} that records
 224      * the lookup class of the caller as the new previous lookup class with
 225      * {@code PRIVATE} access but no {@code MODULE} access.
 226      * <p>
 227      * The resulting {@code Lookup} object has no {@code ORIGINAL} access.
 228      *
 229      * @param targetClass the target class
 230      * @param caller the caller lookup object
 231      * @return a lookup object for the target class, with private access
 232      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or void or array class
 233      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 234      * @throws SecurityException if denied by the security manager
 235      * @throws IllegalAccessException if any of the other access checks specified above fails
 236      * @since 9
 237      * @see Lookup#dropLookupMode
 238      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 239      */
 240     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 241         if (caller.allowedModes == Lookup.TRUSTED) {
 242             return new Lookup(targetClass);
 243         }
 244 
 245         @SuppressWarnings("removal")
 246         SecurityManager sm = System.getSecurityManager();
 247         if (sm != null) sm.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 248         if (targetClass.isPrimitive())
 249             throw new IllegalArgumentException(targetClass + " is a primitive class");
 250         if (targetClass.isArray())
 251             throw new IllegalArgumentException(targetClass + " is an array class");
 252         // Ensure that we can reason accurately about private and module access.
 253         int requireAccess = Lookup.PRIVATE|Lookup.MODULE;
 254         if ((caller.lookupModes() & requireAccess) != requireAccess)
 255             throw new IllegalAccessException("caller does not have PRIVATE and MODULE lookup mode");
 256 
 257         // previous lookup class is never set if it has MODULE access
 258         assert caller.previousLookupClass() == null;
 259 
 260         Class<?> callerClass = caller.lookupClass();
 261         Module callerModule = callerClass.getModule();  // M1
 262         Module targetModule = targetClass.getModule();  // M2
 263         Class<?> newPreviousClass = null;
 264         int newModes = Lookup.FULL_POWER_MODES & ~Lookup.ORIGINAL;
 265 
 266         if (targetModule != callerModule) {
 267             if (!callerModule.canRead(targetModule))
 268                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 269             if (targetModule.isNamed()) {
 270                 String pn = targetClass.getPackageName();
 271                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 272                 if (!targetModule.isOpen(pn, callerModule))
 273                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 274             }
 275 
 276             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 277             newPreviousClass = callerClass;
 278             newModes &= ~Lookup.MODULE;
 279         }
 280         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 281     }
 282 
 283     /**
 284      * Returns the <em>class data</em> associated with the lookup class
 285      * of the given {@code caller} lookup object, or {@code null}.
 286      *
 287      * <p> A hidden class with class data can be created by calling
 288      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 289      * Lookup::defineHiddenClassWithClassData}.
 290      * This method will cause the static class initializer of the lookup
 291      * class of the given {@code caller} lookup object be executed if
 292      * it has not been initialized.
 293      *
 294      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 295      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 296      * {@code null} is returned if this method is called on the lookup object
 297      * on these classes.
 298      *
 299      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 300      * must have {@linkplain Lookup#ORIGINAL original access}
 301      * in order to retrieve the class data.
 302      *
 303      * @apiNote
 304      * This method can be called as a bootstrap method for a dynamically computed
 305      * constant.  A framework can create a hidden class with class data, for
 306      * example that can be {@code Class} or {@code MethodHandle} object.
 307      * The class data is accessible only to the lookup object
 308      * created by the original caller but inaccessible to other members
 309      * in the same nest.  If a framework passes security sensitive objects
 310      * to a hidden class via class data, it is recommended to load the value
 311      * of class data as a dynamically computed constant instead of storing
 312      * the class data in private static field(s) which are accessible to
 313      * other nestmates.
 314      *
 315      * @param <T> the type to cast the class data object to
 316      * @param caller the lookup context describing the class performing the
 317      * operation (normally stacked by the JVM)
 318      * @param name must be {@link ConstantDescs#DEFAULT_NAME}
 319      *             ({@code "_"})
 320      * @param type the type of the class data
 321      * @return the value of the class data if present in the lookup class;
 322      * otherwise {@code null}
 323      * @throws IllegalArgumentException if name is not {@code "_"}
 324      * @throws IllegalAccessException if the lookup context does not have
 325      * {@linkplain Lookup#ORIGINAL original} access
 326      * @throws ClassCastException if the class data cannot be converted to
 327      * the given {@code type}
 328      * @throws NullPointerException if {@code caller} or {@code type} argument
 329      * is {@code null}
 330      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 331      * @see MethodHandles#classDataAt(Lookup, String, Class, int)
 332      * @since 16
 333      * @jvms 5.5 Initialization
 334      */
 335      public static <T> T classData(Lookup caller, String name, Class<T> type) throws IllegalAccessException {
 336          Objects.requireNonNull(caller);
 337          Objects.requireNonNull(type);
 338          if (!ConstantDescs.DEFAULT_NAME.equals(name)) {
 339              throw new IllegalArgumentException("name must be \"_\": " + name);
 340          }
 341 
 342          if ((caller.lookupModes() & Lookup.ORIGINAL) != Lookup.ORIGINAL)  {
 343              throw new IllegalAccessException(caller + " does not have ORIGINAL access");
 344          }
 345 
 346          Object classdata = classData(caller.lookupClass());
 347          if (classdata == null) return null;
 348 
 349          try {
 350              return BootstrapMethodInvoker.widenAndCast(classdata, type);
 351          } catch (RuntimeException|Error e) {
 352              throw e; // let CCE and other runtime exceptions through
 353          } catch (Throwable e) {
 354              throw new InternalError(e);
 355          }
 356     }
 357 
 358     /*
 359      * Returns the class data set by the VM in the Class::classData field.
 360      *
 361      * This is also invoked by LambdaForms as it cannot use condy via
 362      * MethodHandles::classData due to bootstrapping issue.
 363      */
 364     static Object classData(Class<?> c) {
 365         UNSAFE.ensureClassInitialized(c);
 366         return SharedSecrets.getJavaLangAccess().classData(c);
 367     }
 368 
 369     /**
 370      * Returns the element at the specified index in the
 371      * {@linkplain #classData(Lookup, String, Class) class data},
 372      * if the class data associated with the lookup class
 373      * of the given {@code caller} lookup object is a {@code List}.
 374      * If the class data is not present in this lookup class, this method
 375      * returns {@code null}.
 376      *
 377      * <p> A hidden class with class data can be created by calling
 378      * {@link Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 379      * Lookup::defineHiddenClassWithClassData}.
 380      * This method will cause the static class initializer of the lookup
 381      * class of the given {@code caller} lookup object be executed if
 382      * it has not been initialized.
 383      *
 384      * <p> A hidden class created by {@link Lookup#defineHiddenClass(byte[], boolean, Lookup.ClassOption...)
 385      * Lookup::defineHiddenClass} and non-hidden classes have no class data.
 386      * {@code null} is returned if this method is called on the lookup object
 387      * on these classes.
 388      *
 389      * <p> The {@linkplain Lookup#lookupModes() lookup modes} for this lookup
 390      * must have {@linkplain Lookup#ORIGINAL original access}
 391      * in order to retrieve the class data.
 392      *
 393      * @apiNote
 394      * This method can be called as a bootstrap method for a dynamically computed
 395      * constant.  A framework can create a hidden class with class data, for
 396      * example that can be {@code List.of(o1, o2, o3....)} containing more than
 397      * one object and use this method to load one element at a specific index.
 398      * The class data is accessible only to the lookup object
 399      * created by the original caller but inaccessible to other members
 400      * in the same nest.  If a framework passes security sensitive objects
 401      * to a hidden class via class data, it is recommended to load the value
 402      * of class data as a dynamically computed constant instead of storing
 403      * the class data in private static field(s) which are accessible to other
 404      * nestmates.
 405      *
 406      * @param <T> the type to cast the result object to
 407      * @param caller the lookup context describing the class performing the
 408      * operation (normally stacked by the JVM)
 409      * @param name must be {@link java.lang.constant.ConstantDescs#DEFAULT_NAME}
 410      *             ({@code "_"})
 411      * @param type the type of the element at the given index in the class data
 412      * @param index index of the element in the class data
 413      * @return the element at the given index in the class data
 414      * if the class data is present; otherwise {@code null}
 415      * @throws IllegalArgumentException if name is not {@code "_"}
 416      * @throws IllegalAccessException if the lookup context does not have
 417      * {@linkplain Lookup#ORIGINAL original} access
 418      * @throws ClassCastException if the class data cannot be converted to {@code List}
 419      * or the element at the specified index cannot be converted to the given type
 420      * @throws IndexOutOfBoundsException if the index is out of range
 421      * @throws NullPointerException if {@code caller} or {@code type} argument is
 422      * {@code null}; or if unboxing operation fails because
 423      * the element at the given index is {@code null}
 424      *
 425      * @since 16
 426      * @see #classData(Lookup, String, Class)
 427      * @see Lookup#defineHiddenClassWithClassData(byte[], Object, boolean, Lookup.ClassOption...)
 428      */
 429     public static <T> T classDataAt(Lookup caller, String name, Class<T> type, int index)
 430             throws IllegalAccessException
 431     {
 432         @SuppressWarnings("unchecked")
 433         List<Object> classdata = (List<Object>)classData(caller, name, List.class);
 434         if (classdata == null) return null;
 435 
 436         try {
 437             Object element = classdata.get(index);
 438             return BootstrapMethodInvoker.widenAndCast(element, type);
 439         } catch (RuntimeException|Error e) {
 440             throw e; // let specified exceptions and other runtime exceptions/errors through
 441         } catch (Throwable e) {
 442             throw new InternalError(e);
 443         }
 444     }
 445 
 446     /**
 447      * Performs an unchecked "crack" of a
 448      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 449      * The result is as if the user had obtained a lookup object capable enough
 450      * to crack the target method handle, called
 451      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 452      * on the target to obtain its symbolic reference, and then called
 453      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 454      * to resolve the symbolic reference to a member.
 455      * <p>
 456      * If there is a security manager, its {@code checkPermission} method
 457      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 458      * @param <T> the desired type of the result, either {@link Member} or a subtype
 459      * @param target a direct method handle to crack into symbolic reference components
 460      * @param expected a class object representing the desired result type {@code T}
 461      * @return a reference to the method, constructor, or field object
 462      * @throws    SecurityException if the caller is not privileged to call {@code setAccessible}
 463      * @throws    NullPointerException if either argument is {@code null}
 464      * @throws    IllegalArgumentException if the target is not a direct method handle
 465      * @throws    ClassCastException if the member is not of the expected type
 466      * @since 1.8
 467      */
 468     public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) {
 469         @SuppressWarnings("removal")
 470         SecurityManager smgr = System.getSecurityManager();
 471         if (smgr != null)  smgr.checkPermission(SecurityConstants.ACCESS_PERMISSION);
 472         Lookup lookup = Lookup.IMPL_LOOKUP;  // use maximally privileged lookup
 473         return lookup.revealDirect(target).reflectAs(expected, lookup);
 474     }
 475 
 476     /**
 477      * A <em>lookup object</em> is a factory for creating method handles,
 478      * when the creation requires access checking.
 479      * Method handles do not perform
 480      * access checks when they are called, but rather when they are created.
 481      * Therefore, method handle access
 482      * restrictions must be enforced when a method handle is created.
 483      * The caller class against which those restrictions are enforced
 484      * is known as the {@linkplain #lookupClass() lookup class}.
 485      * <p>
 486      * A lookup class which needs to create method handles will call
 487      * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
 488      * When the {@code Lookup} factory object is created, the identity of the lookup class is
 489      * determined, and securely stored in the {@code Lookup} object.
 490      * The lookup class (or its delegates) may then use factory methods
 491      * on the {@code Lookup} object to create method handles for access-checked members.
 492      * This includes all methods, constructors, and fields which are allowed to the lookup class,
 493      * even private ones.
 494      *
 495      * <h2><a id="lookups"></a>Lookup Factory Methods</h2>
 496      * The factory methods on a {@code Lookup} object correspond to all major
 497      * use cases for methods, constructors, and fields.
 498      * Each method handle created by a factory method is the functional
 499      * equivalent of a particular <em>bytecode behavior</em>.
 500      * (Bytecode behaviors are described in section {@jvms 5.4.3.5} of
 501      * the Java Virtual Machine Specification.)
 502      * Here is a summary of the correspondence between these factory methods and
 503      * the behavior of the resulting method handles:
 504      * <table class="striped">
 505      * <caption style="display:none">lookup method behaviors</caption>
 506      * <thead>
 507      * <tr>
 508      *     <th scope="col"><a id="equiv"></a>lookup expression</th>
 509      *     <th scope="col">member</th>
 510      *     <th scope="col">bytecode behavior</th>
 511      * </tr>
 512      * </thead>
 513      * <tbody>
 514      * <tr>
 515      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</th>
 516      *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 517      * </tr>
 518      * <tr>
 519      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</th>
 520      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (FT) C.f;}</td>
 521      * </tr>
 522      * <tr>
 523      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</th>
 524      *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
 525      * </tr>
 526      * <tr>
 527      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</th>
 528      *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
 529      * </tr>
 530      * <tr>
 531      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</th>
 532      *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
 533      * </tr>
 534      * <tr>
 535      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</th>
 536      *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
 537      * </tr>
 538      * <tr>
 539      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</th>
 540      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 541      * </tr>
 542      * <tr>
 543      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</th>
 544      *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
 545      * </tr>
 546      * <tr>
 547      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</th>
 548      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td>
 549      * </tr>
 550      * <tr>
 551      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</th>
 552      *     <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td>
 553      * </tr>
 554      * <tr>
 555      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</th>
 556      *     <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td>
 557      * </tr>
 558      * <tr>
 559      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</th>
 560      *     <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td>
 561      * </tr>
 562      * <tr>
 563      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#unreflectSpecial lookup.unreflectSpecial(aMethod,this.class)}</th>
 564      *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
 565      * </tr>
 566      * <tr>
 567      *     <th scope="row">{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</th>
 568      *     <td>{@code class C { ... }}</td><td>{@code C.class;}</td>
 569      * </tr>
 570      * </tbody>
 571      * </table>
 572      *
 573      * Here, the type {@code C} is the class or interface being searched for a member,
 574      * documented as a parameter named {@code refc} in the lookup methods.
 575      * The method type {@code MT} is composed from the return type {@code T}
 576      * and the sequence of argument types {@code A*}.
 577      * The constructor also has a sequence of argument types {@code A*} and
 578      * is deemed to return the newly-created object of type {@code C}.
 579      * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}.
 580      * The formal parameter {@code this} stands for the self-reference of type {@code C};
 581      * if it is present, it is always the leading argument to the method handle invocation.
 582      * (In the case of some {@code protected} members, {@code this} may be
 583      * restricted in type to the lookup class; see below.)
 584      * The name {@code arg} stands for all the other method handle arguments.
 585      * In the code examples for the Core Reflection API, the name {@code thisOrNull}
 586      * stands for a null reference if the accessed method or field is static,
 587      * and {@code this} otherwise.
 588      * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand
 589      * for reflective objects corresponding to the given members declared in type {@code C}.
 590      * <p>
 591      * The bytecode behavior for a {@code findClass} operation is a load of a constant class,
 592      * as if by {@code ldc CONSTANT_Class}.
 593      * The behavior is represented, not as a method handle, but directly as a {@code Class} constant.
 594      * <p>
 595      * In cases where the given member is of variable arity (i.e., a method or constructor)
 596      * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}.
 597      * In all other cases, the returned method handle will be of fixed arity.
 598      * <p style="font-size:smaller;">
 599      * <em>Discussion:</em>
 600      * The equivalence between looked-up method handles and underlying
 601      * class members and bytecode behaviors
 602      * can break down in a few ways:
 603      * <ul style="font-size:smaller;">
 604      * <li>If {@code C} is not symbolically accessible from the lookup class's loader,
 605      * the lookup can still succeed, even when there is no equivalent
 606      * Java expression or bytecoded constant.
 607      * <li>Likewise, if {@code T} or {@code MT}
 608      * is not symbolically accessible from the lookup class's loader,
 609      * the lookup can still succeed.
 610      * For example, lookups for {@code MethodHandle.invokeExact} and
 611      * {@code MethodHandle.invoke} will always succeed, regardless of requested type.
 612      * <li>If there is a security manager installed, it can forbid the lookup
 613      * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>).
 614      * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle}
 615      * constant is not subject to security manager checks.
 616      * <li>If the looked-up method has a
 617      * <a href="MethodHandle.html#maxarity">very large arity</a>,
 618      * the method handle creation may fail with an
 619      * {@code IllegalArgumentException}, due to the method handle type having
 620      * <a href="MethodHandle.html#maxarity">too many parameters.</a>
 621      * </ul>
 622      *
 623      * <h2><a id="access"></a>Access checking</h2>
 624      * Access checks are applied in the factory methods of {@code Lookup},
 625      * when a method handle is created.
 626      * This is a key difference from the Core Reflection API, since
 627      * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
 628      * performs access checking against every caller, on every call.
 629      * <p>
 630      * All access checks start from a {@code Lookup} object, which
 631      * compares its recorded lookup class against all requests to
 632      * create method handles.
 633      * A single {@code Lookup} object can be used to create any number
 634      * of access-checked method handles, all checked against a single
 635      * lookup class.
 636      * <p>
 637      * A {@code Lookup} object can be shared with other trusted code,
 638      * such as a metaobject protocol.
 639      * A shared {@code Lookup} object delegates the capability
 640      * to create method handles on private members of the lookup class.
 641      * Even if privileged code uses the {@code Lookup} object,
 642      * the access checking is confined to the privileges of the
 643      * original lookup class.
 644      * <p>
 645      * A lookup can fail, because
 646      * the containing class is not accessible to the lookup class, or
 647      * because the desired class member is missing, or because the
 648      * desired class member is not accessible to the lookup class, or
 649      * because the lookup object is not trusted enough to access the member.
 650      * In the case of a field setter function on a {@code final} field,
 651      * finality enforcement is treated as a kind of access control,
 652      * and the lookup will fail, except in special cases of
 653      * {@link Lookup#unreflectSetter Lookup.unreflectSetter}.
 654      * In any of these cases, a {@code ReflectiveOperationException} will be
 655      * thrown from the attempted lookup.  The exact class will be one of
 656      * the following:
 657      * <ul>
 658      * <li>NoSuchMethodException &mdash; if a method is requested but does not exist
 659      * <li>NoSuchFieldException &mdash; if a field is requested but does not exist
 660      * <li>IllegalAccessException &mdash; if the member exists but an access check fails
 661      * </ul>
 662      * <p>
 663      * In general, the conditions under which a method handle may be
 664      * looked up for a method {@code M} are no more restrictive than the conditions
 665      * under which the lookup class could have compiled, verified, and resolved a call to {@code M}.
 666      * Where the JVM would raise exceptions like {@code NoSuchMethodError},
 667      * a method handle lookup will generally raise a corresponding
 668      * checked exception, such as {@code NoSuchMethodException}.
 669      * And the effect of invoking the method handle resulting from the lookup
 670      * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a>
 671      * to executing the compiled, verified, and resolved call to {@code M}.
 672      * The same point is true of fields and constructors.
 673      * <p style="font-size:smaller;">
 674      * <em>Discussion:</em>
 675      * Access checks only apply to named and reflected methods,
 676      * constructors, and fields.
 677      * Other method handle creation methods, such as
 678      * {@link MethodHandle#asType MethodHandle.asType},
 679      * do not require any access checks, and are used
 680      * independently of any {@code Lookup} object.
 681      * <p>
 682      * If the desired member is {@code protected}, the usual JVM rules apply,
 683      * including the requirement that the lookup class must either be in the
 684      * same package as the desired member, or must inherit that member.
 685      * (See the Java Virtual Machine Specification, sections {@jvms
 686      * 4.9.2}, {@jvms 5.4.3.5}, and {@jvms 6.4}.)
 687      * In addition, if the desired member is a non-static field or method
 688      * in a different package, the resulting method handle may only be applied
 689      * to objects of the lookup class or one of its subclasses.
 690      * This requirement is enforced by narrowing the type of the leading
 691      * {@code this} parameter from {@code C}
 692      * (which will necessarily be a superclass of the lookup class)
 693      * to the lookup class itself.
 694      * <p>
 695      * The JVM imposes a similar requirement on {@code invokespecial} instruction,
 696      * that the receiver argument must match both the resolved method <em>and</em>
 697      * the current class.  Again, this requirement is enforced by narrowing the
 698      * type of the leading parameter to the resulting method handle.
 699      * (See the Java Virtual Machine Specification, section {@jvms 4.10.1.9}.)
 700      * <p>
 701      * The JVM represents constructors and static initializer blocks as internal methods
 702      * with special names ({@code "<init>"} and {@code "<clinit>"}).
 703      * The internal syntax of invocation instructions allows them to refer to such internal
 704      * methods as if they were normal methods, but the JVM bytecode verifier rejects them.
 705      * A lookup of such an internal method will produce a {@code NoSuchMethodException}.
 706      * <p>
 707      * If the relationship between nested types is expressed directly through the
 708      * {@code NestHost} and {@code NestMembers} attributes
 709      * (see the Java Virtual Machine Specification, sections {@jvms
 710      * 4.7.28} and {@jvms 4.7.29}),
 711      * then the associated {@code Lookup} object provides direct access to
 712      * the lookup class and all of its nestmates
 713      * (see {@link java.lang.Class#getNestHost Class.getNestHost}).
 714      * Otherwise, access between nested classes is obtained by the Java compiler creating
 715      * a wrapper method to access a private method of another class in the same nest.
 716      * For example, a nested class {@code C.D}
 717      * can access private members within other related classes such as
 718      * {@code C}, {@code C.D.E}, or {@code C.B},
 719      * but the Java compiler may need to generate wrapper methods in
 720      * those related classes.  In such cases, a {@code Lookup} object on
 721      * {@code C.E} would be unable to access those private members.
 722      * A workaround for this limitation is the {@link Lookup#in Lookup.in} method,
 723      * which can transform a lookup on {@code C.E} into one on any of those other
 724      * classes, without special elevation of privilege.
 725      * <p>
 726      * The accesses permitted to a given lookup object may be limited,
 727      * according to its set of {@link #lookupModes lookupModes},
 728      * to a subset of members normally accessible to the lookup class.
 729      * For example, the {@link MethodHandles#publicLookup publicLookup}
 730      * method produces a lookup object which is only allowed to access
 731      * public members in public classes of exported packages.
 732      * The caller sensitive method {@link MethodHandles#lookup lookup}
 733      * produces a lookup object with full capabilities relative to
 734      * its caller class, to emulate all supported bytecode behaviors.
 735      * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object
 736      * with fewer access modes than the original lookup object.
 737      *
 738      * <p style="font-size:smaller;">
 739      * <a id="privacc"></a>
 740      * <em>Discussion of private and module access:</em>
 741      * We say that a lookup has <em>private access</em>
 742      * if its {@linkplain #lookupModes lookup modes}
 743      * include the possibility of accessing {@code private} members
 744      * (which includes the private members of nestmates).
 745      * As documented in the relevant methods elsewhere,
 746      * only lookups with private access possess the following capabilities:
 747      * <ul style="font-size:smaller;">
 748      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 749      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 750      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 751      *     for classes accessible to the lookup class
 752      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 753      *     within the same package member
 754      * </ul>
 755      * <p style="font-size:smaller;">
 756      * Similarly, a lookup with module access ensures that the original lookup creator was
 757      * a member in the same module as the lookup class.
 758      * <p style="font-size:smaller;">
 759      * Private and module access are independently determined modes; a lookup may have
 760      * either or both or neither.  A lookup which possesses both access modes is said to
 761      * possess {@linkplain #hasFullPrivilegeAccess() full privilege access}.
 762      * <p style="font-size:smaller;">
 763      * A lookup with <em>original access</em> ensures that this lookup is created by
 764      * the original lookup class and the bootstrap method invoked by the VM.
 765      * Such a lookup with original access also has private and module access
 766      * which has the following additional capability:
 767      * <ul style="font-size:smaller;">
 768      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 769      *     such as {@code Class.forName}
 770      * <li>obtain the {@linkplain MethodHandles#classData(Lookup, String, Class)
 771      * class data} associated with the lookup class</li>
 772      * </ul>
 773      * <p style="font-size:smaller;">
 774      * Each of these permissions is a consequence of the fact that a lookup object
 775      * with private access can be securely traced back to an originating class,
 776      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 777      * can be reliably determined and emulated by method handles.
 778      *
 779      * <h2><a id="cross-module-lookup"></a>Cross-module lookups</h2>
 780      * When a lookup class in one module {@code M1} accesses a class in another module
 781      * {@code M2}, extra access checking is performed beyond the access mode bits.
 782      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 783      * can access public types in {@code M2} when {@code M2} is readable to {@code M1}
 784      * and when the type is in a package of {@code M2} that is exported to
 785      * at least {@code M1}.
 786      * <p>
 787      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 788      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 789      * MethodHandles.privateLookupIn} methods.
 790      * Teleporting across modules will always record the original lookup class as
 791      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 792      * and drops {@link Lookup#MODULE MODULE} access.
 793      * If the target class is in the same module as the lookup class {@code C},
 794      * then the target class becomes the new lookup class
 795      * and there is no change to the previous lookup class.
 796      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 797      * {@code C} becomes the new previous lookup class
 798      * and the target class becomes the new lookup class.
 799      * In that case, if there was already a previous lookup class in {@code M0},
 800      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 801      * drops all privileges.
 802      * For example,
 803      * <blockquote><pre>
 804      * {@code
 805      * Lookup lookup = MethodHandles.lookup();   // in class C
 806      * Lookup lookup2 = lookup.in(D.class);
 807      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 808      * }</pre></blockquote>
 809      * <p>
 810      * The {@link #lookup()} factory method produces a {@code Lookup} object
 811      * with {@code null} previous lookup class.
 812      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 813      * to class {@code D} without elevation of privileges.
 814      * If {@code C} and {@code D} are in the same module,
 815      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 816      * same previous lookup class as the original {@code lookup}, or
 817      * {@code null} if not present.
 818      * <p>
 819      * When a {@code Lookup} teleports from a class
 820      * in one nest to another nest, {@code PRIVATE} access is dropped.
 821      * When a {@code Lookup} teleports from a class in one package to
 822      * another package, {@code PACKAGE} access is dropped.
 823      * When a {@code Lookup} teleports from a class in one module to another module,
 824      * {@code MODULE} access is dropped.
 825      * Teleporting across modules drops the ability to access non-exported classes
 826      * in both the module of the new lookup class and the module of the old lookup class
 827      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 828      * A {@code Lookup} can teleport back and forth to a class in the module of
 829      * the lookup class and the module of the previous class lookup.
 830      * Teleporting across modules can only decrease access but cannot increase it.
 831      * Teleporting to some third module drops all accesses.
 832      * <p>
 833      * In the above example, if {@code C} and {@code D} are in different modules,
 834      * {@code lookup2} records {@code D} as its lookup class and
 835      * {@code C} as its previous lookup class and {@code lookup2} has only
 836      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 837      * {@code C}'s module and {@code D}'s module.
 838      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 839      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 840      * class {@code D} is recorded as its previous lookup class.
 841      * <p>
 842      * Teleporting across modules restricts access to the public types that
 843      * both the lookup class and the previous lookup class can equally access
 844      * (see below).
 845      * <p>
 846      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 847      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 848      * and create a new {@code Lookup} with <a href="#privacc">private access</a>
 849      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 850      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 851      * to call {@code privateLookupIn}.
 852      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 853      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 854      * produces a new {@code Lookup} on {@code T} with full capabilities.
 855      * A {@code lookup} on {@code C} is also allowed
 856      * to do deep reflection on {@code T} in another module {@code M2} if
 857      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 858      * the package containing {@code T} to at least {@code M1}.
 859      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 860      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 861      * The resulting {@code Lookup} can be used to do member lookup or teleport
 862      * to another lookup class by calling {@link #in Lookup::in}.  But
 863      * it cannot be used to obtain another private {@code Lookup} by calling
 864      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 865      * because it has no {@code MODULE} access.
 866      *
 867      * <h2><a id="module-access-check"></a>Cross-module access checks</h2>
 868      *
 869      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 870      * allows cross-module access. The access checking is performed with respect
 871      * to both the lookup class and the previous lookup class if present.
 872      * <p>
 873      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 874      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 875      * exported unconditionally}.
 876      * <p>
 877      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 878      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 879      * that are readable to {@code M1} and the type is in a package that is exported
 880      * at least to {@code M1}.
 881      * <p>
 882      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 883      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 884      * the intersection of all public types that are accessible to {@code M1}
 885      * with all public types that are accessible to {@code M0}. {@code M0}
 886      * reads {@code M1} and hence the set of accessible types includes:
 887      *
 888      * <ul>
 889      * <li>unconditional-exported packages from {@code M1}</li>
 890      * <li>unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</li>
 891      * <li>
 892      *     unconditional-exported packages from a third module {@code M2}if both {@code M0}
 893      *     and {@code M1} read {@code M2}
 894      * </li>
 895      * <li>qualified-exported packages from {@code M1} to {@code M0}</li>
 896      * <li>qualified-exported packages from {@code M0} to {@code M1} if {@code M1} reads {@code M0}</li>
 897      * <li>
 898      *     qualified-exported packages from a third module {@code M2} to both {@code M0} and
 899      *     {@code M1} if both {@code M0} and {@code M1} read {@code M2}
 900      * </li>
 901      * </ul>
 902      *
 903      * <h2><a id="access-modes"></a>Access modes</h2>
 904      *
 905      * The table below shows the access modes of a {@code Lookup} produced by
 906      * any of the following factory or transformation methods:
 907      * <ul>
 908      * <li>{@link #lookup() MethodHandles::lookup}</li>
 909      * <li>{@link #publicLookup() MethodHandles::publicLookup}</li>
 910      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles::privateLookupIn}</li>
 911      * <li>{@link Lookup#in Lookup::in}</li>
 912      * <li>{@link Lookup#dropLookupMode(int) Lookup::dropLookupMode}</li>
 913      * </ul>
 914      *
 915      * <table class="striped">
 916      * <caption style="display:none">
 917      * Access mode summary
 918      * </caption>
 919      * <thead>
 920      * <tr>
 921      * <th scope="col">Lookup object</th>
 922      * <th style="text-align:center">original</th>
 923      * <th style="text-align:center">protected</th>
 924      * <th style="text-align:center">private</th>
 925      * <th style="text-align:center">package</th>
 926      * <th style="text-align:center">module</th>
 927      * <th style="text-align:center">public</th>
 928      * </tr>
 929      * </thead>
 930      * <tbody>
 931      * <tr>
 932      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 933      * <td style="text-align:center">ORI</td>
 934      * <td style="text-align:center">PRO</td>
 935      * <td style="text-align:center">PRI</td>
 936      * <td style="text-align:center">PAC</td>
 937      * <td style="text-align:center">MOD</td>
 938      * <td style="text-align:center">1R</td>
 939      * </tr>
 940      * <tr>
 941      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 942      * <td></td>
 943      * <td></td>
 944      * <td></td>
 945      * <td style="text-align:center">PAC</td>
 946      * <td style="text-align:center">MOD</td>
 947      * <td style="text-align:center">1R</td>
 948      * </tr>
 949      * <tr>
 950      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 951      * <td></td>
 952      * <td></td>
 953      * <td></td>
 954      * <td></td>
 955      * <td style="text-align:center">MOD</td>
 956      * <td style="text-align:center">1R</td>
 957      * </tr>
 958      * <tr>
 959      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 960      * <td></td>
 961      * <td></td>
 962      * <td></td>
 963      * <td></td>
 964      * <td></td>
 965      * <td style="text-align:center">2R</td>
 966      * </tr>
 967      * <tr>
 968      * <th scope="row" style="text-align:left">{@code CL.in(D).in(C)} hop back to module</th>
 969      * <td></td>
 970      * <td></td>
 971      * <td></td>
 972      * <td></td>
 973      * <td></td>
 974      * <td style="text-align:center">2R</td>
 975      * </tr>
 976      * <tr>
 977      * <th scope="row" style="text-align:left">{@code PRI1 = privateLookupIn(C1,CL)}</th>
 978      * <td></td>
 979      * <td style="text-align:center">PRO</td>
 980      * <td style="text-align:center">PRI</td>
 981      * <td style="text-align:center">PAC</td>
 982      * <td style="text-align:center">MOD</td>
 983      * <td style="text-align:center">1R</td>
 984      * </tr>
 985      * <tr>
 986      * <th scope="row" style="text-align:left">{@code PRI1a = privateLookupIn(C,PRI1)}</th>
 987      * <td></td>
 988      * <td style="text-align:center">PRO</td>
 989      * <td style="text-align:center">PRI</td>
 990      * <td style="text-align:center">PAC</td>
 991      * <td style="text-align:center">MOD</td>
 992      * <td style="text-align:center">1R</td>
 993      * </tr>
 994      * <tr>
 995      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} same package</th>
 996      * <td></td>
 997      * <td></td>
 998      * <td></td>
 999      * <td style="text-align:center">PAC</td>
1000      * <td style="text-align:center">MOD</td>
1001      * <td style="text-align:center">1R</td>
1002      * </tr>
1003      * <tr>
1004      * <th scope="row" style="text-align:left">{@code PRI1.in(C1)} different package</th>
1005      * <td></td>
1006      * <td></td>
1007      * <td></td>
1008      * <td></td>
1009      * <td style="text-align:center">MOD</td>
1010      * <td style="text-align:center">1R</td>
1011      * </tr>
1012      * <tr>
1013      * <th scope="row" style="text-align:left">{@code PRI1.in(D)} different module</th>
1014      * <td></td>
1015      * <td></td>
1016      * <td></td>
1017      * <td></td>
1018      * <td></td>
1019      * <td style="text-align:center">2R</td>
1020      * </tr>
1021      * <tr>
1022      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PROTECTED)}</th>
1023      * <td></td>
1024      * <td></td>
1025      * <td style="text-align:center">PRI</td>
1026      * <td style="text-align:center">PAC</td>
1027      * <td style="text-align:center">MOD</td>
1028      * <td style="text-align:center">1R</td>
1029      * </tr>
1030      * <tr>
1031      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PRIVATE)}</th>
1032      * <td></td>
1033      * <td></td>
1034      * <td></td>
1035      * <td style="text-align:center">PAC</td>
1036      * <td style="text-align:center">MOD</td>
1037      * <td style="text-align:center">1R</td>
1038      * </tr>
1039      * <tr>
1040      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PACKAGE)}</th>
1041      * <td></td>
1042      * <td></td>
1043      * <td></td>
1044      * <td></td>
1045      * <td style="text-align:center">MOD</td>
1046      * <td style="text-align:center">1R</td>
1047      * </tr>
1048      * <tr>
1049      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(MODULE)}</th>
1050      * <td></td>
1051      * <td></td>
1052      * <td></td>
1053      * <td></td>
1054      * <td></td>
1055      * <td style="text-align:center">1R</td>
1056      * </tr>
1057      * <tr>
1058      * <th scope="row" style="text-align:left">{@code PRI1.dropLookupMode(PUBLIC)}</th>
1059      * <td></td>
1060      * <td></td>
1061      * <td></td>
1062      * <td></td>
1063      * <td></td>
1064      * <td style="text-align:center">none</td>
1065      * <tr>
1066      * <th scope="row" style="text-align:left">{@code PRI2 = privateLookupIn(D,CL)}</th>
1067      * <td></td>
1068      * <td style="text-align:center">PRO</td>
1069      * <td style="text-align:center">PRI</td>
1070      * <td style="text-align:center">PAC</td>
1071      * <td></td>
1072      * <td style="text-align:center">2R</td>
1073      * </tr>
1074      * <tr>
1075      * <th scope="row" style="text-align:left">{@code privateLookupIn(D,PRI1)}</th>
1076      * <td></td>
1077      * <td style="text-align:center">PRO</td>
1078      * <td style="text-align:center">PRI</td>
1079      * <td style="text-align:center">PAC</td>
1080      * <td></td>
1081      * <td style="text-align:center">2R</td>
1082      * </tr>
1083      * <tr>
1084      * <th scope="row" style="text-align:left">{@code privateLookupIn(C,PRI2)} fails</th>
1085      * <td></td>
1086      * <td></td>
1087      * <td></td>
1088      * <td></td>
1089      * <td></td>
1090      * <td style="text-align:center">IAE</td>
1091      * </tr>
1092      * <tr>
1093      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} same package</th>
1094      * <td></td>
1095      * <td></td>
1096      * <td></td>
1097      * <td style="text-align:center">PAC</td>
1098      * <td></td>
1099      * <td style="text-align:center">2R</td>
1100      * </tr>
1101      * <tr>
1102      * <th scope="row" style="text-align:left">{@code PRI2.in(D2)} different package</th>
1103      * <td></td>
1104      * <td></td>
1105      * <td></td>
1106      * <td></td>
1107      * <td></td>
1108      * <td style="text-align:center">2R</td>
1109      * </tr>
1110      * <tr>
1111      * <th scope="row" style="text-align:left">{@code PRI2.in(C1)} hop back to module</th>
1112      * <td></td>
1113      * <td></td>
1114      * <td></td>
1115      * <td></td>
1116      * <td></td>
1117      * <td style="text-align:center">2R</td>
1118      * </tr>
1119      * <tr>
1120      * <th scope="row" style="text-align:left">{@code PRI2.in(E)} hop to third module</th>
1121      * <td></td>
1122      * <td></td>
1123      * <td></td>
1124      * <td></td>
1125      * <td></td>
1126      * <td style="text-align:center">none</td>
1127      * </tr>
1128      * <tr>
1129      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PROTECTED)}</th>
1130      * <td></td>
1131      * <td></td>
1132      * <td style="text-align:center">PRI</td>
1133      * <td style="text-align:center">PAC</td>
1134      * <td></td>
1135      * <td style="text-align:center">2R</td>
1136      * </tr>
1137      * <tr>
1138      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PRIVATE)}</th>
1139      * <td></td>
1140      * <td></td>
1141      * <td></td>
1142      * <td style="text-align:center">PAC</td>
1143      * <td></td>
1144      * <td style="text-align:center">2R</td>
1145      * </tr>
1146      * <tr>
1147      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PACKAGE)}</th>
1148      * <td></td>
1149      * <td></td>
1150      * <td></td>
1151      * <td></td>
1152      * <td></td>
1153      * <td style="text-align:center">2R</td>
1154      * </tr>
1155      * <tr>
1156      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(MODULE)}</th>
1157      * <td></td>
1158      * <td></td>
1159      * <td></td>
1160      * <td></td>
1161      * <td></td>
1162      * <td style="text-align:center">2R</td>
1163      * </tr>
1164      * <tr>
1165      * <th scope="row" style="text-align:left">{@code PRI2.dropLookupMode(PUBLIC)}</th>
1166      * <td></td>
1167      * <td></td>
1168      * <td></td>
1169      * <td></td>
1170      * <td></td>
1171      * <td style="text-align:center">none</td>
1172      * </tr>
1173      * <tr>
1174      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PROTECTED)}</th>
1175      * <td></td>
1176      * <td></td>
1177      * <td style="text-align:center">PRI</td>
1178      * <td style="text-align:center">PAC</td>
1179      * <td style="text-align:center">MOD</td>
1180      * <td style="text-align:center">1R</td>
1181      * </tr>
1182      * <tr>
1183      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PRIVATE)}</th>
1184      * <td></td>
1185      * <td></td>
1186      * <td></td>
1187      * <td style="text-align:center">PAC</td>
1188      * <td style="text-align:center">MOD</td>
1189      * <td style="text-align:center">1R</td>
1190      * </tr>
1191      * <tr>
1192      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PACKAGE)}</th>
1193      * <td></td>
1194      * <td></td>
1195      * <td></td>
1196      * <td></td>
1197      * <td style="text-align:center">MOD</td>
1198      * <td style="text-align:center">1R</td>
1199      * </tr>
1200      * <tr>
1201      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(MODULE)}</th>
1202      * <td></td>
1203      * <td></td>
1204      * <td></td>
1205      * <td></td>
1206      * <td></td>
1207      * <td style="text-align:center">1R</td>
1208      * </tr>
1209      * <tr>
1210      * <th scope="row" style="text-align:left">{@code CL.dropLookupMode(PUBLIC)}</th>
1211      * <td></td>
1212      * <td></td>
1213      * <td></td>
1214      * <td></td>
1215      * <td></td>
1216      * <td style="text-align:center">none</td>
1217      * </tr>
1218      * <tr>
1219      * <th scope="row" style="text-align:left">{@code PUB = publicLookup()}</th>
1220      * <td></td>
1221      * <td></td>
1222      * <td></td>
1223      * <td></td>
1224      * <td></td>
1225      * <td style="text-align:center">U</td>
1226      * </tr>
1227      * <tr>
1228      * <th scope="row" style="text-align:left">{@code PUB.in(D)} different module</th>
1229      * <td></td>
1230      * <td></td>
1231      * <td></td>
1232      * <td></td>
1233      * <td></td>
1234      * <td style="text-align:center">U</td>
1235      * </tr>
1236      * <tr>
1237      * <th scope="row" style="text-align:left">{@code PUB.in(D).in(E)} third module</th>
1238      * <td></td>
1239      * <td></td>
1240      * <td></td>
1241      * <td></td>
1242      * <td></td>
1243      * <td style="text-align:center">U</td>
1244      * </tr>
1245      * <tr>
1246      * <th scope="row" style="text-align:left">{@code PUB.dropLookupMode(UNCONDITIONAL)}</th>
1247      * <td></td>
1248      * <td></td>
1249      * <td></td>
1250      * <td></td>
1251      * <td></td>
1252      * <td style="text-align:center">none</td>
1253      * </tr>
1254      * <tr>
1255      * <th scope="row" style="text-align:left">{@code privateLookupIn(C1,PUB)} fails</th>
1256      * <td></td>
1257      * <td></td>
1258      * <td></td>
1259      * <td></td>
1260      * <td></td>
1261      * <td style="text-align:center">IAE</td>
1262      * </tr>
1263      * <tr>
1264      * <th scope="row" style="text-align:left">{@code ANY.in(X)}, for inaccessible {@code X}</th>
1265      * <td></td>
1266      * <td></td>
1267      * <td></td>
1268      * <td></td>
1269      * <td></td>
1270      * <td style="text-align:center">none</td>
1271      * </tr>
1272      * </tbody>
1273      * </table>
1274      *
1275      * <p>
1276      * Notes:
1277      * <ul>
1278      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1279      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1280      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1281      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1282      * <li>{@code ORI} indicates {@link #ORIGINAL} bit set,
1283      *     {@code PRO} indicates {@link #PROTECTED} bit set,
1284      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1285      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1286      *     {@code MOD} indicates {@link #MODULE} bit set,
1287      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1288      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1289      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1290      * <li>Public access comes in three kinds:
1291      * <ul>
1292      * <li>unconditional ({@code U}): the lookup assumes readability.
1293      *     The lookup has {@code null} previous lookup class.
1294      * <li>one-module-reads ({@code 1R}): the module access checking is
1295      *     performed with respect to the lookup class.  The lookup has {@code null}
1296      *     previous lookup class.
1297      * <li>two-module-reads ({@code 2R}): the module access checking is
1298      *     performed with respect to the lookup class and the previous lookup class.
1299      *     The lookup has a non-null previous lookup class which is in a
1300      *     different module from the current lookup class.
1301      * </ul>
1302      * <li>Any attempt to reach a third module loses all access.</li>
1303      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1304      * all access modes are dropped.</li>
1305      * </ul>
1306      *
1307      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1308      * Although bytecode instructions can only refer to classes in
1309      * a related class loader, this API can search for methods in any
1310      * class, as long as a reference to its {@code Class} object is
1311      * available.  Such cross-loader references are also possible with the
1312      * Core Reflection API, and are impossible to bytecode instructions
1313      * such as {@code invokestatic} or {@code getfield}.
1314      * There is a {@linkplain java.lang.SecurityManager security manager API}
1315      * to allow applications to check such cross-loader references.
1316      * These checks apply to both the {@code MethodHandles.Lookup} API
1317      * and the Core Reflection API
1318      * (as found on {@link java.lang.Class Class}).
1319      * <p>
1320      * If a security manager is present, member and class lookups are subject to
1321      * additional checks.
1322      * From one to three calls are made to the security manager.
1323      * Any of these calls can refuse access by throwing a
1324      * {@link java.lang.SecurityException SecurityException}.
1325      * Define {@code smgr} as the security manager,
1326      * {@code lookc} as the lookup class of the current lookup object,
1327      * {@code refc} as the containing class in which the member
1328      * is being sought, and {@code defc} as the class in which the
1329      * member is actually defined.
1330      * (If a class or other type is being accessed,
1331      * the {@code refc} and {@code defc} values are the class itself.)
1332      * The value {@code lookc} is defined as <em>not present</em>
1333      * if the current lookup object does not have
1334      * {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1335      * The calls are made according to the following rules:
1336      * <ul>
1337      * <li><b>Step 1:</b>
1338      *     If {@code lookc} is not present, or if its class loader is not
1339      *     the same as or an ancestor of the class loader of {@code refc},
1340      *     then {@link SecurityManager#checkPackageAccess
1341      *     smgr.checkPackageAccess(refcPkg)} is called,
1342      *     where {@code refcPkg} is the package of {@code refc}.
1343      * <li><b>Step 2a:</b>
1344      *     If the retrieved member is not public and
1345      *     {@code lookc} is not present, then
1346      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1347      *     with {@code RuntimePermission("accessDeclaredMembers")} is called.
1348      * <li><b>Step 2b:</b>
1349      *     If the retrieved class has a {@code null} class loader,
1350      *     and {@code lookc} is not present, then
1351      *     {@link SecurityManager#checkPermission smgr.checkPermission}
1352      *     with {@code RuntimePermission("getClassLoader")} is called.
1353      * <li><b>Step 3:</b>
1354      *     If the retrieved member is not public,
1355      *     and if {@code lookc} is not present,
1356      *     and if {@code defc} and {@code refc} are different,
1357      *     then {@link SecurityManager#checkPackageAccess
1358      *     smgr.checkPackageAccess(defcPkg)} is called,
1359      *     where {@code defcPkg} is the package of {@code defc}.
1360      * </ul>
1361      * Security checks are performed after other access checks have passed.
1362      * Therefore, the above rules presuppose a member or class that is public,
1363      * or else that is being accessed from a lookup class that has
1364      * rights to access the member or class.
1365      * <p>
1366      * If a security manager is present and the current lookup object does not have
1367      * {@linkplain #hasFullPrivilegeAccess() full privilege access}, then
1368      * {@link #defineClass(byte[]) defineClass},
1369      * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass},
1370      * {@link #defineHiddenClassWithClassData(byte[], Object, boolean, ClassOption...)
1371      * defineHiddenClassWithClassData}
1372      * calls {@link SecurityManager#checkPermission smgr.checkPermission}
1373      * with {@code RuntimePermission("defineClass")}.
1374      *
1375      * <h2><a id="callsens"></a>Caller sensitive methods</h2>
1376      * A small number of Java methods have a special property called caller sensitivity.
1377      * A <em>caller-sensitive</em> method can behave differently depending on the
1378      * identity of its immediate caller.
1379      * <p>
1380      * If a method handle for a caller-sensitive method is requested,
1381      * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply,
1382      * but they take account of the lookup class in a special way.
1383      * The resulting method handle behaves as if it were called
1384      * from an instruction contained in the lookup class,
1385      * so that the caller-sensitive method detects the lookup class.
1386      * (By contrast, the invoker of the method handle is disregarded.)
1387      * Thus, in the case of caller-sensitive methods,
1388      * different lookup classes may give rise to
1389      * differently behaving method handles.
1390      * <p>
1391      * In cases where the lookup object is
1392      * {@link MethodHandles#publicLookup() publicLookup()},
1393      * or some other lookup object without the
1394      * {@linkplain #ORIGINAL original access},
1395      * the lookup class is disregarded.
1396      * In such cases, no caller-sensitive method handle can be created,
1397      * access is forbidden, and the lookup fails with an
1398      * {@code IllegalAccessException}.
1399      * <p style="font-size:smaller;">
1400      * <em>Discussion:</em>
1401      * For example, the caller-sensitive method
1402      * {@link java.lang.Class#forName(String) Class.forName(x)}
1403      * can return varying classes or throw varying exceptions,
1404      * depending on the class loader of the class that calls it.
1405      * A public lookup of {@code Class.forName} will fail, because
1406      * there is no reasonable way to determine its bytecode behavior.
1407      * <p style="font-size:smaller;">
1408      * If an application caches method handles for broad sharing,
1409      * it should use {@code publicLookup()} to create them.
1410      * If there is a lookup of {@code Class.forName}, it will fail,
1411      * and the application must take appropriate action in that case.
1412      * It may be that a later lookup, perhaps during the invocation of a
1413      * bootstrap method, can incorporate the specific identity
1414      * of the caller, making the method accessible.
1415      * <p style="font-size:smaller;">
1416      * The function {@code MethodHandles.lookup} is caller sensitive
1417      * so that there can be a secure foundation for lookups.
1418      * Nearly all other methods in the JSR 292 API rely on lookup
1419      * objects to check access requests.
1420      *
1421      * @revised 9
1422      */
1423     public static final
1424     class Lookup {
1425         /** The class on behalf of whom the lookup is being performed. */
1426         private final Class<?> lookupClass;
1427 
1428         /** previous lookup class */
1429         private final Class<?> prevLookupClass;
1430 
1431         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1432         private final int allowedModes;
1433 
1434         static {
1435             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1436         }
1437 
1438         /** A single-bit mask representing {@code public} access,
1439          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1440          *  The value, {@code 0x01}, happens to be the same as the value of the
1441          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1442          *  <p>
1443          *  A {@code Lookup} with this lookup mode performs cross-module access check
1444          *  with respect to the {@linkplain #lookupClass() lookup class} and
1445          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1446          */
1447         public static final int PUBLIC = Modifier.PUBLIC;
1448 
1449         /** A single-bit mask representing {@code private} access,
1450          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1451          *  The value, {@code 0x02}, happens to be the same as the value of the
1452          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1453          */
1454         public static final int PRIVATE = Modifier.PRIVATE;
1455 
1456         /** A single-bit mask representing {@code protected} access,
1457          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1458          *  The value, {@code 0x04}, happens to be the same as the value of the
1459          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1460          */
1461         public static final int PROTECTED = Modifier.PROTECTED;
1462 
1463         /** A single-bit mask representing {@code package} access (default access),
1464          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1465          *  The value is {@code 0x08}, which does not correspond meaningfully to
1466          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1467          */
1468         public static final int PACKAGE = Modifier.STATIC;
1469 
1470         /** A single-bit mask representing {@code module} access,
1471          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1472          *  The value is {@code 0x10}, which does not correspond meaningfully to
1473          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1474          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1475          *  with this lookup mode can access all public types in the module of the
1476          *  lookup class and public types in packages exported by other modules
1477          *  to the module of the lookup class.
1478          *  <p>
1479          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1480          *  previous lookup class} is always {@code null}.
1481          *
1482          *  @since 9
1483          */
1484         public static final int MODULE = PACKAGE << 1;
1485 
1486         /** A single-bit mask representing {@code unconditional} access
1487          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1488          *  The value is {@code 0x20}, which does not correspond meaningfully to
1489          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1490          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1491          *  java.lang.Module#canRead(java.lang.Module) readability}.
1492          *  This lookup mode can access all public members of public types
1493          *  of all modules when the type is in a package that is {@link
1494          *  java.lang.Module#isExported(String) exported unconditionally}.
1495          *
1496          *  <p>
1497          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1498          *  previous lookup class} is always {@code null}.
1499          *
1500          *  @since 9
1501          *  @see #publicLookup()
1502          */
1503         public static final int UNCONDITIONAL = PACKAGE << 2;
1504 
1505         /** A single-bit mask representing {@code original} access
1506          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1507          *  The value is {@code 0x40}, which does not correspond meaningfully to
1508          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1509          *
1510          *  <p>
1511          *  If this lookup mode is set, the {@code Lookup} object must be
1512          *  created by the original lookup class by calling
1513          *  {@link MethodHandles#lookup()} method or by a bootstrap method
1514          *  invoked by the VM.  The {@code Lookup} object with this lookup
1515          *  mode has {@linkplain #hasFullPrivilegeAccess() full privilege access}.
1516          *
1517          *  @since 16
1518          */
1519         public static final int ORIGINAL = PACKAGE << 3;
1520 
1521         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL | ORIGINAL);
1522         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);   // with original access
1523         private static final int TRUSTED   = -1;
1524 
1525         /*
1526          * Adjust PUBLIC => PUBLIC|MODULE|ORIGINAL|UNCONDITIONAL
1527          * Adjust 0 => PACKAGE
1528          */
1529         private static int fixmods(int mods) {
1530             mods &= (ALL_MODES - PACKAGE - MODULE - ORIGINAL - UNCONDITIONAL);
1531             if (Modifier.isPublic(mods))
1532                 mods |= UNCONDITIONAL;
1533             return (mods != 0) ? mods : PACKAGE;
1534         }
1535 
1536         /** Tells which class is performing the lookup.  It is this class against
1537          *  which checks are performed for visibility and access permissions.
1538          *  <p>
1539          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1540          *  access checks are performed against both the lookup class and the previous lookup class.
1541          *  <p>
1542          *  The class implies a maximum level of access permission,
1543          *  but the permissions may be additionally limited by the bitmask
1544          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1545          *  can be accessed.
1546          *  @return the lookup class, on behalf of which this lookup object finds members
1547          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1548          */
1549         public Class<?> lookupClass() {
1550             return lookupClass;
1551         }
1552 
1553         /** Reports a lookup class in another module that this lookup object
1554          * was previously teleported from, or {@code null}.
1555          * <p>
1556          * A {@code Lookup} object produced by the factory methods, such as the
1557          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1558          * has {@code null} previous lookup class.
1559          * A {@code Lookup} object has a non-null previous lookup class
1560          * when this lookup was teleported from an old lookup class
1561          * in one module to a new lookup class in another module.
1562          *
1563          * @return the lookup class in another module that this lookup object was
1564          *         previously teleported from, or {@code null}
1565          * @since 14
1566          * @see #in(Class)
1567          * @see MethodHandles#privateLookupIn(Class, Lookup)
1568          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1569          */
1570         public Class<?> previousLookupClass() {
1571             return prevLookupClass;
1572         }
1573 
1574         // This is just for calling out to MethodHandleImpl.
1575         private Class<?> lookupClassOrNull() {
1576             return (allowedModes == TRUSTED) ? null : lookupClass;
1577         }
1578 
1579         /** Tells which access-protection classes of members this lookup object can produce.
1580          *  The result is a bit-mask of the bits
1581          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1582          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1583          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1584          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1585          *  {@linkplain #MODULE MODULE (0x10)},
1586          *  {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)},
1587          *  and {@linkplain #ORIGINAL ORIGINAL (0x40)}.
1588          *  <p>
1589          *  A freshly-created lookup object
1590          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1591          *  all possible bits set, except {@code UNCONDITIONAL}.
1592          *  A lookup object on a new lookup class
1593          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1594          *  may have some mode bits set to zero.
1595          *  Mode bits can also be
1596          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#dropLookupMode directly cleared}.
1597          *  Once cleared, mode bits cannot be restored from the downgraded lookup object.
1598          *  The purpose of this is to restrict access via the new lookup object,
1599          *  so that it can access only names which can be reached by the original
1600          *  lookup object, and also by the new lookup class.
1601          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1602          *  @see #in
1603          *  @see #dropLookupMode
1604          *
1605          *  @revised 9
1606          */
1607         public int lookupModes() {
1608             return allowedModes & ALL_MODES;
1609         }
1610 
1611         /** Embody the current class (the lookupClass) as a lookup class
1612          * for method handle creation.
1613          * Must be called by from a method in this package,
1614          * which in turn is called by a method not in this package.
1615          */
1616         Lookup(Class<?> lookupClass) {
1617             this(lookupClass, null, FULL_POWER_MODES);
1618         }
1619 
1620         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1621             assert lookupClass.isPrimaryType();
1622             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1623                     && prevLookupClass.getModule() != lookupClass.getModule());
1624             assert !lookupClass.isArray() && !lookupClass.isPrimitive();
1625             this.lookupClass = lookupClass;
1626             this.prevLookupClass = prevLookupClass;
1627             this.allowedModes = allowedModes;
1628         }
1629 
1630         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1631             // make sure we haven't accidentally picked up a privileged class:
1632             checkUnprivilegedlookupClass(lookupClass);
1633             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1634         }
1635 
1636         /**
1637          * Creates a lookup on the specified new lookup class.
1638          * The resulting object will report the specified
1639          * class as its own {@link #lookupClass() lookupClass}.
1640          *
1641          * <p>
1642          * However, the resulting {@code Lookup} object is guaranteed
1643          * to have no more access capabilities than the original.
1644          * In particular, access capabilities can be lost as follows:<ul>
1645          * <li>If the new lookup class is different from the old lookup class,
1646          * i.e. {@link #ORIGINAL ORIGINAL} access is lost.
1647          * <li>If the new lookup class is in a different module from the old one,
1648          * i.e. {@link #MODULE MODULE} access is lost.
1649          * <li>If the new lookup class is in a different package
1650          * than the old one, protected and default (package) members will not be accessible,
1651          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1652          * <li>If the new lookup class is not within the same package member
1653          * as the old one, private members will not be accessible, and protected members
1654          * will not be accessible by virtue of inheritance,
1655          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1656          * (Protected members may continue to be accessible because of package sharing.)
1657          * <li>If the new lookup class is not
1658          * {@linkplain #accessClass(Class) accessible} to this lookup,
1659          * then no members, not even public members, will be accessible
1660          * i.e. all access modes are lost.
1661          * <li>If the new lookup class, the old lookup class and the previous lookup class
1662          * are all in different modules i.e. teleporting to a third module,
1663          * all access modes are lost.
1664          * </ul>
1665          * <p>
1666          * The new previous lookup class is chosen as follows:
1667          * <ul>
1668          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1669          * the new previous lookup class is {@code null}.
1670          * <li>If the new lookup class is in the same module as the old lookup class,
1671          * the new previous lookup class is the old previous lookup class.
1672          * <li>If the new lookup class is in a different module from the old lookup class,
1673          * the new previous lookup class is the old lookup class.
1674          *</ul>
1675          * <p>
1676          * The resulting lookup's capabilities for loading classes
1677          * (used during {@link #findClass} invocations)
1678          * are determined by the lookup class' loader,
1679          * which may change due to this operation.
1680          *
1681          * @param requestedLookupClass the desired lookup class for the new lookup object
1682          * @return a lookup object which reports the desired lookup class, or the same object
1683          * if there is no change
1684          * @throws IllegalArgumentException if {@code requestedLookupClass} is a primitive type or void or array class
1685          * @throws NullPointerException if the argument is null
1686          *
1687          * @revised 9
1688          * @see #accessClass(Class)
1689          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1690          */
1691         public Lookup in(Class<?> requestedLookupClass) {
1692             Objects.requireNonNull(requestedLookupClass);
1693             if (requestedLookupClass.isPrimitive())
1694                 throw new IllegalArgumentException(requestedLookupClass + " is a primitive class");
1695             if (requestedLookupClass.isArray())
1696                 throw new IllegalArgumentException(requestedLookupClass + " is an array class");
1697 
1698             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1699                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1700             if (requestedLookupClass == this.lookupClass)
1701                 return this;  // keep same capabilities
1702             int newModes = (allowedModes & FULL_POWER_MODES) & ~ORIGINAL;
1703             Module fromModule = this.lookupClass.getModule();
1704             Module targetModule = requestedLookupClass.getModule();
1705             Class<?> plc = this.previousLookupClass();
1706             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1707                 assert plc == null;
1708                 newModes = UNCONDITIONAL;
1709             } else if (fromModule != targetModule) {
1710                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1711                     // allow hopping back and forth between fromModule and plc's module
1712                     // but not the third module
1713                     newModes = 0;
1714                 }
1715                 // drop MODULE access
1716                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1717                 // teleport from this lookup class
1718                 plc = this.lookupClass;
1719             }
1720             if ((newModes & PACKAGE) != 0
1721                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1722                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1723             }
1724             // Allow nestmate lookups to be created without special privilege:
1725             if ((newModes & PRIVATE) != 0
1726                     && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1727                 newModes &= ~(PRIVATE|PROTECTED);
1728             }
1729             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1730                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1731                 // The requested class it not accessible from the lookup class.
1732                 // No permissions.
1733                 newModes = 0;
1734             }
1735             return newLookup(requestedLookupClass, plc, newModes);
1736         }
1737 
1738         /**
1739          * Creates a lookup on the same lookup class which this lookup object
1740          * finds members, but with a lookup mode that has lost the given lookup mode.
1741          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1742          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED},
1743          * {@link #PRIVATE PRIVATE}, {@link #ORIGINAL ORIGINAL}, or
1744          * {@link #UNCONDITIONAL UNCONDITIONAL}.
1745          *
1746          * <p> If this lookup is a {@linkplain MethodHandles#publicLookup() public lookup},
1747          * this lookup has {@code UNCONDITIONAL} mode set and it has no other mode set.
1748          * When dropping {@code UNCONDITIONAL} on a public lookup then the resulting
1749          * lookup has no access.
1750          *
1751          * <p> If this lookup is not a public lookup, then the following applies
1752          * regardless of its {@linkplain #lookupModes() lookup modes}.
1753          * {@link #PROTECTED PROTECTED} and {@link #ORIGINAL ORIGINAL} are always
1754          * dropped and so the resulting lookup mode will never have these access
1755          * capabilities. When dropping {@code PACKAGE}
1756          * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
1757          * access. When dropping {@code MODULE} then the resulting lookup will not
1758          * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access.
1759          * When dropping {@code PUBLIC} then the resulting lookup has no access.
1760          *
1761          * @apiNote
1762          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1763          * delegate non-public access within the package of the lookup class without
1764          * conferring  <a href="MethodHandles.Lookup.html#privacc">private access</a>.
1765          * A lookup with {@code MODULE} but not
1766          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1767          * the module of the lookup class without conferring package access.
1768          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1769          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1770          * to public classes accessible to both the module of the lookup class
1771          * and the module of the previous lookup class.
1772          *
1773          * @param modeToDrop the lookup mode to drop
1774          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1775          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1776          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE}, {@code ORIGINAL}
1777          * or {@code UNCONDITIONAL}
1778          * @see MethodHandles#privateLookupIn
1779          * @since 9
1780          */
1781         public Lookup dropLookupMode(int modeToDrop) {
1782             int oldModes = lookupModes();
1783             int newModes = oldModes & ~(modeToDrop | PROTECTED | ORIGINAL);
1784             switch (modeToDrop) {
1785                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1786                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1787                 case PACKAGE: newModes &= ~(PRIVATE); break;
1788                 case PROTECTED:
1789                 case PRIVATE:
1790                 case ORIGINAL:
1791                 case UNCONDITIONAL: break;
1792                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1793             }
1794             if (newModes == oldModes) return this;  // return self if no change
1795             return newLookup(lookupClass(), previousLookupClass(), newModes);
1796         }
1797 
1798         /**
1799          * Creates and links a class or interface from {@code bytes}
1800          * with the same class loader and in the same runtime package and
1801          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1802          * {@linkplain #lookupClass() lookup class} as if calling
1803          * {@link ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1804          * ClassLoader::defineClass}.
1805          *
1806          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1807          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1808          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1809          * that the lookup object was created by a caller in the runtime package (or derived
1810          * from a lookup originally created by suitably privileged code to a target class in
1811          * the runtime package). </p>
1812          *
1813          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1814          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1815          * same package as the lookup class. </p>
1816          *
1817          * <p> This method does not run the class initializer. The class initializer may
1818          * run at a later time, as detailed in section 12.4 of the <em>The Java Language
1819          * Specification</em>. </p>
1820          *
1821          * <p> If there is a security manager and this lookup does not have {@linkplain
1822          * #hasFullPrivilegeAccess() full privilege access}, its {@code checkPermission} method
1823          * is first called to check {@code RuntimePermission("defineClass")}. </p>
1824          *
1825          * @param bytes the class bytes
1826          * @return the {@code Class} object for the class
1827          * @throws IllegalAccessException if this lookup does not have {@code PACKAGE} access
1828          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1829          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
1830          * than the lookup class or {@code bytes} is not a class or interface
1831          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
1832          * @throws VerifyError if the newly created class cannot be verified
1833          * @throws LinkageError if the newly created class cannot be linked for any other reason
1834          * @throws SecurityException if a security manager is present and it
1835          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1836          * @throws NullPointerException if {@code bytes} is {@code null}
1837          * @since 9
1838          * @see Lookup#privateLookupIn
1839          * @see Lookup#dropLookupMode
1840          * @see ClassLoader#defineClass(String,byte[],int,int,ProtectionDomain)
1841          */
1842         public Class<?> defineClass(byte[] bytes) throws IllegalAccessException {
1843             ensureDefineClassPermission();
1844             if ((lookupModes() & PACKAGE) == 0)
1845                 throw new IllegalAccessException("Lookup does not have PACKAGE access");
1846             return makeClassDefiner(bytes.clone()).defineClass(false);
1847         }
1848 
1849         private void ensureDefineClassPermission() {
1850             if (allowedModes == TRUSTED)  return;
1851 
1852             if (!hasFullPrivilegeAccess()) {
1853                 @SuppressWarnings("removal")
1854                 SecurityManager sm = System.getSecurityManager();
1855                 if (sm != null)
1856                     sm.checkPermission(new RuntimePermission("defineClass"));
1857             }
1858         }
1859 
1860         /**
1861          * The set of class options that specify whether a hidden class created by
1862          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1863          * Lookup::defineHiddenClass} method is dynamically added as a new member
1864          * to the nest of a lookup class and/or whether a hidden class has
1865          * a strong relationship with the class loader marked as its defining loader.
1866          *
1867          * @since 15
1868          */
1869         public enum ClassOption {
1870             /**
1871              * Specifies that a hidden class be added to {@linkplain Class#getNestHost nest}
1872              * of a lookup class as a nestmate.
1873              *
1874              * <p> A hidden nestmate class has access to the private members of all
1875              * classes and interfaces in the same nest.
1876              *
1877              * @see Class#getNestHost()
1878              */
1879             NESTMATE(NESTMATE_CLASS),
1880 
1881             /**
1882              * Specifies that a hidden class has a <em>strong</em>
1883              * relationship with the class loader marked as its defining loader,
1884              * as a normal class or interface has with its own defining loader.
1885              * This means that the hidden class may be unloaded if and only if
1886              * its defining loader is not reachable and thus may be reclaimed
1887              * by a garbage collector (JLS {@jls 12.7}).
1888              *
1889              * <p> By default, a hidden class or interface may be unloaded
1890              * even if the class loader that is marked as its defining loader is
1891              * <a href="../ref/package-summary.html#reachability">reachable</a>.
1892 
1893              *
1894              * @jls 12.7 Unloading of Classes and Interfaces
1895              */
1896             STRONG(STRONG_LOADER_LINK);
1897 
1898             /* the flag value is used by VM at define class time */
1899             private final int flag;
1900             ClassOption(int flag) {
1901                 this.flag = flag;
1902             }
1903 
1904             static int optionsToFlag(Set<ClassOption> options) {
1905                 int flags = 0;
1906                 for (ClassOption cp : options) {
1907                     flags |= cp.flag;
1908                 }
1909                 return flags;
1910             }
1911         }
1912 
1913         /**
1914          * Creates a <em>hidden</em> class or interface from {@code bytes},
1915          * returning a {@code Lookup} on the newly created class or interface.
1916          *
1917          * <p> Ordinarily, a class or interface {@code C} is created by a class loader,
1918          * which either defines {@code C} directly or delegates to another class loader.
1919          * A class loader defines {@code C} directly by invoking
1920          * {@link ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1921          * ClassLoader::defineClass}, which causes the Java Virtual Machine
1922          * to derive {@code C} from a purported representation in {@code class} file format.
1923          * In situations where use of a class loader is undesirable, a class or interface
1924          * {@code C} can be created by this method instead. This method is capable of
1925          * defining {@code C}, and thereby creating it, without invoking
1926          * {@code ClassLoader::defineClass}.
1927          * Instead, this method defines {@code C} as if by arranging for
1928          * the Java Virtual Machine to derive a nonarray class or interface {@code C}
1929          * from a purported representation in {@code class} file format
1930          * using the following rules:
1931          *
1932          * <ol>
1933          * <li> The {@linkplain #lookupModes() lookup modes} for this {@code Lookup}
1934          * must include {@linkplain #hasFullPrivilegeAccess() full privilege} access.
1935          * This level of access is needed to create {@code C} in the module
1936          * of the lookup class of this {@code Lookup}.</li>
1937          *
1938          * <li> The purported representation in {@code bytes} must be a {@code ClassFile}
1939          * structure (JVMS {@jvms 4.1}) of a supported major and minor version.
1940          * The major and minor version may differ from the {@code class} file version
1941          * of the lookup class of this {@code Lookup}.</li>
1942          *
1943          * <li> The value of {@code this_class} must be a valid index in the
1944          * {@code constant_pool} table, and the entry at that index must be a valid
1945          * {@code CONSTANT_Class_info} structure. Let {@code N} be the binary name
1946          * encoded in internal form that is specified by this structure. {@code N} must
1947          * denote a class or interface in the same package as the lookup class.</li>
1948          *
1949          * <li> Let {@code CN} be the string {@code N + "." + <suffix>},
1950          * where {@code <suffix>} is an unqualified name.
1951          *
1952          * <p> Let {@code newBytes} be the {@code ClassFile} structure given by
1953          * {@code bytes} with an additional entry in the {@code constant_pool} table,
1954          * indicating a {@code CONSTANT_Utf8_info} structure for {@code CN}, and
1955          * where the {@code CONSTANT_Class_info} structure indicated by {@code this_class}
1956          * refers to the new {@code CONSTANT_Utf8_info} structure.
1957          *
1958          * <p> Let {@code L} be the defining class loader of the lookup class of this {@code Lookup}.
1959          *
1960          * <p> {@code C} is derived with name {@code CN}, class loader {@code L}, and
1961          * purported representation {@code newBytes} as if by the rules of JVMS {@jvms 5.3.5},
1962          * with the following adjustments:
1963          * <ul>
1964          * <li> The constant indicated by {@code this_class} is permitted to specify a name
1965          * that includes a single {@code "."} character, even though this is not a valid
1966          * binary class or interface name in internal form.</li>
1967          *
1968          * <li> The Java Virtual Machine marks {@code L} as the defining class loader of {@code C},
1969          * but no class loader is recorded as an initiating class loader of {@code C}.</li>
1970          *
1971          * <li> {@code C} is considered to have the same runtime
1972          * {@linkplain Class#getPackage() package}, {@linkplain Class#getModule() module}
1973          * and {@linkplain java.security.ProtectionDomain protection domain}
1974          * as the lookup class of this {@code Lookup}.
1975          * <li> Let {@code GN} be the binary name obtained by taking {@code N}
1976          * (a binary name encoded in internal form) and replacing ASCII forward slashes with
1977          * ASCII periods. For the instance of {@link java.lang.Class} representing {@code C}:
1978          * <ul>
1979          * <li> {@link Class#getName()} returns the string {@code GN + "/" + <suffix>},
1980          *      even though this is not a valid binary class or interface name.</li>
1981          * <li> {@link Class#descriptorString()} returns the string
1982          *      {@code "L" + N + "." + <suffix> + ";"},
1983          *      even though this is not a valid type descriptor name.</li>
1984          * <li> {@link Class#describeConstable()} returns an empty optional as {@code C}
1985          *      cannot be described in {@linkplain java.lang.constant.ClassDesc nominal form}.</li>
1986          * </ul>
1987          * </ul>
1988          * </li>
1989          * </ol>
1990          *
1991          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1992          * Linkage occurs as specified in JVMS {@jvms 5.4.3}, with the following adjustments:
1993          * <ul>
1994          * <li> During verification, whenever it is necessary to load the class named
1995          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1996          * made of any class loader.</li>
1997          *
1998          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1999          * by {@code this_class}, the symbolic reference is considered to be resolved to
2000          * {@code C} and resolution always succeeds immediately.</li>
2001          * </ul>
2002          *
2003          * <p> If the {@code initialize} parameter is {@code true},
2004          * then {@code C} is initialized by the Java Virtual Machine.
2005          *
2006          * <p> The newly created class or interface {@code C} serves as the
2007          * {@linkplain #lookupClass() lookup class} of the {@code Lookup} object
2008          * returned by this method. {@code C} is <em>hidden</em> in the sense that
2009          * no other class or interface can refer to {@code C} via a constant pool entry.
2010          * That is, a hidden class or interface cannot be named as a supertype, a field type,
2011          * a method parameter type, or a method return type by any other class.
2012          * This is because a hidden class or interface does not have a binary name, so
2013          * there is no internal form available to record in any class's constant pool.
2014          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
2015          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
2016          * is not {@linkplain java.instrument/java.lang.instrument.Instrumentation#isModifiableClass(Class)
2017          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
2018          * JVM Tool Interface</a>.
2019          *
2020          * <p> A class or interface created by
2021          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
2022          * a class loader} has a strong relationship with that class loader.
2023          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
2024          * that {@linkplain Class#getClassLoader() defined it}.
2025          * This means that a class created by a class loader may be unloaded if and
2026          * only if its defining loader is not reachable and thus may be reclaimed
2027          * by a garbage collector (JLS {@jls 12.7}).
2028          *
2029          * By default, however, a hidden class or interface may be unloaded even if
2030          * the class loader that is marked as its defining loader is
2031          * <a href="../ref/package-summary.html#reachability">reachable</a>.
2032          * This behavior is useful when a hidden class or interface serves multiple
2033          * classes defined by arbitrary class loaders.  In other cases, a hidden
2034          * class or interface may be linked to a single class (or a small number of classes)
2035          * with the same defining loader as the hidden class or interface.
2036          * In such cases, where the hidden class or interface must be coterminous
2037          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
2038          * option may be passed in {@code options}.
2039          * This arranges for a hidden class to have the same strong relationship
2040          * with the class loader marked as its defining loader,
2041          * as a normal class or interface has with its own defining loader.
2042          *
2043          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
2044          * may still prevent a hidden class or interface from being
2045          * unloaded by ensuring that the {@code Class} object is reachable.
2046          *
2047          * <p> The unloading characteristics are set for each hidden class when it is
2048          * defined, and cannot be changed later.  An advantage of allowing hidden classes
2049          * to be unloaded independently of the class loader marked as their defining loader
2050          * is that a very large number of hidden classes may be created by an application.
2051          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
2052          * just as if normal classes were created by class loaders.
2053          *
2054          * <p> Classes and interfaces in a nest are allowed to have mutual access to
2055          * their private members.  The nest relationship is determined by
2056          * the {@code NestHost} attribute (JVMS {@jvms 4.7.28}) and
2057          * the {@code NestMembers} attribute (JVMS {@jvms 4.7.29}) in a {@code class} file.
2058          * By default, a hidden class belongs to a nest consisting only of itself
2059          * because a hidden class has no binary name.
2060          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
2061          * to create a hidden class or interface {@code C} as a member of a nest.
2062          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
2063          * in the {@code ClassFile} structure from which {@code C} was derived.
2064          * Instead, the following rules determine the nest host of {@code C}:
2065          * <ul>
2066          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
2067          *     been determined, then let {@code H} be the nest host of the lookup class.
2068          *     Otherwise, the nest host of the lookup class is determined using the
2069          *     algorithm in JVMS {@jvms 5.4.4}, yielding {@code H}.</li>
2070          * <li>The nest host of {@code C} is determined to be {@code H},
2071          *     the nest host of the lookup class.</li>
2072          * </ul>
2073          *
2074          * <p> A hidden class or interface may be serializable, but this requires a custom
2075          * serialization mechanism in order to ensure that instances are properly serialized
2076          * and deserialized. The default serialization mechanism supports only classes and
2077          * interfaces that are discoverable by their class name.
2078          *
2079          * @param bytes the bytes that make up the class data,
2080          * in the format of a valid {@code class} file as defined by
2081          * <cite>The Java Virtual Machine Specification</cite>.
2082          * @param initialize if {@code true} the class will be initialized.
2083          * @param options {@linkplain ClassOption class options}
2084          * @return the {@code Lookup} object on the hidden class,
2085          * with {@linkplain #ORIGINAL original} and
2086          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2087          *
2088          * @throws IllegalAccessException if this {@code Lookup} does not have
2089          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2090          * @throws SecurityException if a security manager is present and it
2091          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2092          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2093          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2094          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2095          * than the lookup class or {@code bytes} is not a class or interface
2096          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2097          * @throws IncompatibleClassChangeError if the class or interface named as
2098          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2099          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2100          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2101          * {@code C} is {@code C} itself
2102          * @throws VerifyError if the newly created class cannot be verified
2103          * @throws LinkageError if the newly created class cannot be linked for any other reason
2104          * @throws NullPointerException if any parameter is {@code null}
2105          *
2106          * @since 15
2107          * @see Class#isHidden()
2108          * @jvms 4.2.1 Binary Class and Interface Names
2109          * @jvms 4.2.2 Unqualified Names
2110          * @jvms 4.7.28 The {@code NestHost} Attribute
2111          * @jvms 4.7.29 The {@code NestMembers} Attribute
2112          * @jvms 5.4.3.1 Class and Interface Resolution
2113          * @jvms 5.4.4 Access Control
2114          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2115          * @jvms 5.4 Linking
2116          * @jvms 5.5 Initialization
2117          * @jls 12.7 Unloading of Classes and Interfaces
2118          */
2119         @SuppressWarnings("doclint:reference") // cross-module links
2120         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
2121                 throws IllegalAccessException
2122         {
2123             Objects.requireNonNull(bytes);
2124             Objects.requireNonNull(options);
2125 
2126             ensureDefineClassPermission();
2127             if (!hasFullPrivilegeAccess()) {
2128                 throw new IllegalAccessException(this + " does not have full privilege access");
2129             }
2130 
2131             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false).defineClassAsLookup(initialize);
2132         }
2133 
2134         /**
2135          * Creates a <em>hidden</em> class or interface from {@code bytes} with associated
2136          * {@linkplain MethodHandles#classData(Lookup, String, Class) class data},
2137          * returning a {@code Lookup} on the newly created class or interface.
2138          *
2139          * <p> This method is equivalent to calling
2140          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
2141          * as if the hidden class is injected with a private static final <i>unnamed</i>
2142          * field which is initialized with the given {@code classData} at
2143          * the first instruction of the class initializer.
2144          * The newly created class is linked by the Java Virtual Machine.
2145          *
2146          * <p> The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData}
2147          * and {@link MethodHandles#classDataAt(Lookup, String, Class, int) MethodHandles::classDataAt}
2148          * methods can be used to retrieve the {@code classData}.
2149          *
2150          * @apiNote
2151          * A framework can create a hidden class with class data with one or more
2152          * objects and load the class data as dynamically-computed constant(s)
2153          * via a bootstrap method.  {@link MethodHandles#classData(Lookup, String, Class)
2154          * Class data} is accessible only to the lookup object created by the newly
2155          * defined hidden class but inaccessible to other members in the same nest
2156          * (unlike private static fields that are accessible to nestmates).
2157          * Care should be taken w.r.t. mutability for example when passing
2158          * an array or other mutable structure through the class data.
2159          * Changing any value stored in the class data at runtime may lead to
2160          * unpredictable behavior.
2161          * If the class data is a {@code List}, it is good practice to make it
2162          * unmodifiable for example via {@link List#of List::of}.
2163          *
2164          * @param bytes     the class bytes
2165          * @param classData pre-initialized class data
2166          * @param initialize if {@code true} the class will be initialized.
2167          * @param options   {@linkplain ClassOption class options}
2168          * @return the {@code Lookup} object on the hidden class,
2169          * with {@linkplain #ORIGINAL original} and
2170          * {@linkplain Lookup#hasFullPrivilegeAccess() full privilege} access
2171          *
2172          * @throws IllegalAccessException if this {@code Lookup} does not have
2173          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
2174          * @throws SecurityException if a security manager is present and it
2175          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2176          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
2177          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
2178          * @throws IllegalArgumentException if {@code bytes} denotes a class in a different package
2179          * than the lookup class or {@code bytes} is not a class or interface
2180          * ({@code ACC_MODULE} flag is set in the value of the {@code access_flags} item)
2181          * @throws IncompatibleClassChangeError if the class or interface named as
2182          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
2183          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
2184          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
2185          * {@code C} is {@code C} itself
2186          * @throws VerifyError if the newly created class cannot be verified
2187          * @throws LinkageError if the newly created class cannot be linked for any other reason
2188          * @throws NullPointerException if any parameter is {@code null}
2189          *
2190          * @since 16
2191          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
2192          * @see Class#isHidden()
2193          * @see MethodHandles#classData(Lookup, String, Class)
2194          * @see MethodHandles#classDataAt(Lookup, String, Class, int)
2195          * @jvms 4.2.1 Binary Class and Interface Names
2196          * @jvms 4.2.2 Unqualified Names
2197          * @jvms 4.7.28 The {@code NestHost} Attribute
2198          * @jvms 4.7.29 The {@code NestMembers} Attribute
2199          * @jvms 5.4.3.1 Class and Interface Resolution
2200          * @jvms 5.4.4 Access Control
2201          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
2202          * @jvms 5.4 Linking
2203          * @jvms 5.5 Initialization
2204          * @jls 12.7 Unloading of Classes and Interface
2205          */
2206         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
2207                 throws IllegalAccessException
2208         {
2209             Objects.requireNonNull(bytes);
2210             Objects.requireNonNull(classData);
2211             Objects.requireNonNull(options);
2212 
2213             ensureDefineClassPermission();
2214             if (!hasFullPrivilegeAccess()) {
2215                 throw new IllegalAccessException(this + " does not have full privilege access");
2216             }
2217 
2218             return makeHiddenClassDefiner(bytes.clone(), Set.of(options), false)
2219                        .defineClassAsLookup(initialize, classData);
2220         }
2221 
2222         static class ClassFile {
2223             final String name;
2224             final int accessFlags;
2225             final byte[] bytes;
2226             ClassFile(String name, int accessFlags, byte[] bytes) {
2227                 this.name = name;
2228                 this.accessFlags = accessFlags;
2229                 this.bytes = bytes;
2230             }
2231 
2232             static ClassFile newInstanceNoCheck(String name, byte[] bytes) {
2233                 return new ClassFile(name, 0, bytes);
2234             }
2235 
2236             /**
2237              * This method checks the class file version and the structure of `this_class`.
2238              * and checks if the bytes is a class or interface (ACC_MODULE flag not set)
2239              * that is in the named package.
2240              *
2241              * @throws IllegalArgumentException if ACC_MODULE flag is set in access flags
2242              * or the class is not in the given package name.
2243              */
2244             static ClassFile newInstance(byte[] bytes, String pkgName) {
2245                 int magic = readInt(bytes, 0);
2246                 if (magic != 0xCAFEBABE) {
2247                     throw new ClassFormatError("Incompatible magic value: " + magic);
2248                 }
2249                 int minor = readUnsignedShort(bytes, 4);
2250                 int major = readUnsignedShort(bytes, 6);
2251                 if (!VM.isSupportedClassFileVersion(major, minor)) {
2252                     throw new UnsupportedClassVersionError("Unsupported class file version " + major + "." + minor);
2253                 }
2254 
2255                 String name;
2256                 int accessFlags;
2257                 try {
2258                     ClassReader reader = new ClassReader(bytes);
2259                     // ClassReader::getClassName does not check if `this_class` is CONSTANT_Class_info
2260                     // workaround to read `this_class` using readConst and validate the value
2261                     int thisClass = reader.readUnsignedShort(reader.header + 2);
2262                     Object constant = reader.readConst(thisClass, new char[reader.getMaxStringLength()]);
2263                     if (!(constant instanceof Type type)) {
2264                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2265                     }
2266                     if (!type.getDescriptor().startsWith("L")) {
2267                         throw new ClassFormatError("this_class item: #" + thisClass + " not a CONSTANT_Class_info");
2268                     }
2269                     name = type.getClassName();
2270                     accessFlags = reader.readUnsignedShort(reader.header);
2271                 } catch (RuntimeException e) {
2272                     // ASM exceptions are poorly specified
2273                     ClassFormatError cfe = new ClassFormatError();
2274                     cfe.initCause(e);
2275                     throw cfe;
2276                 }
2277 
2278                 // must be a class or interface
2279                 if ((accessFlags & Opcodes.ACC_MODULE) != 0) {
2280                     throw newIllegalArgumentException("Not a class or interface: ACC_MODULE flag is set");
2281                 }
2282 
2283                 // check if it's in the named package
2284                 int index = name.lastIndexOf('.');
2285                 String pn = (index == -1) ? "" : name.substring(0, index);
2286                 if (!pn.equals(pkgName)) {
2287                     throw newIllegalArgumentException(name + " not in same package as lookup class");
2288                 }
2289 
2290                 return new ClassFile(name, accessFlags, bytes);
2291             }
2292 
2293             private static int readInt(byte[] bytes, int offset) {
2294                 if ((offset+4) > bytes.length) {
2295                     throw new ClassFormatError("Invalid ClassFile structure");
2296                 }
2297                 return ((bytes[offset] & 0xFF) << 24)
2298                         | ((bytes[offset + 1] & 0xFF) << 16)
2299                         | ((bytes[offset + 2] & 0xFF) << 8)
2300                         | (bytes[offset + 3] & 0xFF);
2301             }
2302 
2303             private static int readUnsignedShort(byte[] bytes, int offset) {
2304                 if ((offset+2) > bytes.length) {
2305                     throw new ClassFormatError("Invalid ClassFile structure");
2306                 }
2307                 return ((bytes[offset] & 0xFF) << 8) | (bytes[offset + 1] & 0xFF);
2308             }
2309         }
2310 
2311         /*
2312          * Returns a ClassDefiner that creates a {@code Class} object of a normal class
2313          * from the given bytes.
2314          *
2315          * Caller should make a defensive copy of the arguments if needed
2316          * before calling this factory method.
2317          *
2318          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2319          * {@bytes} denotes a class in a different package than the lookup class
2320          */
2321         private ClassDefiner makeClassDefiner(byte[] bytes) {
2322             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2323             return new ClassDefiner(this, cf, STRONG_LOADER_LINK);
2324         }
2325 
2326         /**
2327          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2328          * from the given bytes.  The name must be in the same package as the lookup class.
2329          *
2330          * Caller should make a defensive copy of the arguments if needed
2331          * before calling this factory method.
2332          *
2333          * @param bytes   class bytes
2334          * @return ClassDefiner that defines a hidden class of the given bytes.
2335          *
2336          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2337          * {@bytes} denotes a class in a different package than the lookup class
2338          */
2339         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2340             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2341             return makeHiddenClassDefiner(cf, Set.of(), false);
2342         }
2343 
2344         /**
2345          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2346          * from the given bytes and options.
2347          * The name must be in the same package as the lookup class.
2348          *
2349          * Caller should make a defensive copy of the arguments if needed
2350          * before calling this factory method.
2351          *
2352          * @param bytes   class bytes
2353          * @param options class options
2354          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2355          * @return ClassDefiner that defines a hidden class of the given bytes and options
2356          *
2357          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
2358          * {@bytes} denotes a class in a different package than the lookup class
2359          */
2360         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2361                                             Set<ClassOption> options,
2362                                             boolean accessVmAnnotations) {
2363             ClassFile cf = ClassFile.newInstance(bytes, lookupClass().getPackageName());
2364             return makeHiddenClassDefiner(cf, options, accessVmAnnotations);
2365         }
2366 
2367         /**
2368          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2369          * from the given bytes and the given options.  No package name check on the given name.
2370          *
2371          * @param name    fully-qualified name that specifies the prefix of the hidden class
2372          * @param bytes   class bytes
2373          * @param options class options
2374          * @return ClassDefiner that defines a hidden class of the given bytes and options.
2375          */
2376         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, Set<ClassOption> options) {
2377             // skip name and access flags validation
2378             return makeHiddenClassDefiner(ClassFile.newInstanceNoCheck(name, bytes), options, false);
2379         }
2380 
2381         /**
2382          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2383          * from the given class file and options.
2384          *
2385          * @param cf ClassFile
2386          * @param options class options
2387          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2388          */
2389         private ClassDefiner makeHiddenClassDefiner(ClassFile cf,
2390                                                     Set<ClassOption> options,
2391                                                     boolean accessVmAnnotations) {
2392             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2393             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2394                 // jdk.internal.vm.annotations are permitted for classes
2395                 // defined to boot loader and platform loader
2396                 flags |= ACCESS_VM_ANNOTATIONS;
2397             }
2398 
2399             return new ClassDefiner(this, cf, flags);
2400         }
2401 
2402         static class ClassDefiner {
2403             private final Lookup lookup;
2404             private final String name;
2405             private final byte[] bytes;
2406             private final int classFlags;
2407 
2408             private ClassDefiner(Lookup lookup, ClassFile cf, int flags) {
2409                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2410                 this.lookup = lookup;
2411                 this.bytes = cf.bytes;
2412                 this.name = cf.name;
2413                 this.classFlags = flags;
2414             }
2415 
2416             String className() {
2417                 return name;
2418             }
2419 
2420             Class<?> defineClass(boolean initialize) {
2421                 return defineClass(initialize, null);
2422             }
2423 
2424             Lookup defineClassAsLookup(boolean initialize) {
2425                 Class<?> c = defineClass(initialize, null);
2426                 return new Lookup(c, null, FULL_POWER_MODES);
2427             }
2428 
2429             /**
2430              * Defines the class of the given bytes and the given classData.
2431              * If {@code initialize} parameter is true, then the class will be initialized.
2432              *
2433              * @param initialize true if the class to be initialized
2434              * @param classData classData or null
2435              * @return the class
2436              *
2437              * @throws LinkageError linkage error
2438              */
2439             Class<?> defineClass(boolean initialize, Object classData) {
2440                 Class<?> lookupClass = lookup.lookupClass();
2441                 ClassLoader loader = lookupClass.getClassLoader();
2442                 ProtectionDomain pd = (loader != null) ? lookup.lookupClassProtectionDomain() : null;
2443                 Class<?> c = SharedSecrets.getJavaLangAccess()
2444                         .defineClass(loader, lookupClass, name, bytes, pd, initialize, classFlags, classData);
2445                 assert !isNestmate() || c.getNestHost() == lookupClass.getNestHost();
2446                 return c;
2447             }
2448 
2449             Lookup defineClassAsLookup(boolean initialize, Object classData) {
2450                 Class<?> c = defineClass(initialize, classData);
2451                 return new Lookup(c, null, FULL_POWER_MODES);
2452             }
2453 
2454             private boolean isNestmate() {
2455                 return (classFlags & NESTMATE_CLASS) != 0;
2456             }
2457         }
2458 
2459         private ProtectionDomain lookupClassProtectionDomain() {
2460             ProtectionDomain pd = cachedProtectionDomain;
2461             if (pd == null) {
2462                 cachedProtectionDomain = pd = SharedSecrets.getJavaLangAccess().protectionDomain(lookupClass);
2463             }
2464             return pd;
2465         }
2466 
2467         // cached protection domain
2468         private volatile ProtectionDomain cachedProtectionDomain;
2469 
2470         // Make sure outer class is initialized first.
2471         static { IMPL_NAMES.getClass(); }
2472 
2473         /** Package-private version of lookup which is trusted. */
2474         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
2475 
2476         /** Version of lookup which is trusted minimally.
2477          *  It can only be used to create method handles to publicly accessible
2478          *  members in packages that are exported unconditionally.
2479          */
2480         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
2481 
2482         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
2483             String name = lookupClass.getName();
2484             if (name.startsWith("java.lang.invoke."))
2485                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
2486         }
2487 
2488         /**
2489          * Displays the name of the class from which lookups are to be made,
2490          * followed by "/" and the name of the {@linkplain #previousLookupClass()
2491          * previous lookup class} if present.
2492          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
2493          * If there are restrictions on the access permitted to this lookup,
2494          * this is indicated by adding a suffix to the class name, consisting
2495          * of a slash and a keyword.  The keyword represents the strongest
2496          * allowed access, and is chosen as follows:
2497          * <ul>
2498          * <li>If no access is allowed, the suffix is "/noaccess".
2499          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
2500          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
2501          * <li>If only public and module access are allowed, the suffix is "/module".
2502          * <li>If public and package access are allowed, the suffix is "/package".
2503          * <li>If public, package, and private access are allowed, the suffix is "/private".
2504          * </ul>
2505          * If none of the above cases apply, it is the case that
2506          * {@linkplain #hasFullPrivilegeAccess() full privilege access}
2507          * (public, module, package, private, and protected) is allowed.
2508          * In this case, no suffix is added.
2509          * This is true only of an object obtained originally from
2510          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
2511          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
2512          * always have restricted access, and will display a suffix.
2513          * <p>
2514          * (It may seem strange that protected access should be
2515          * stronger than private access.  Viewed independently from
2516          * package access, protected access is the first to be lost,
2517          * because it requires a direct subclass relationship between
2518          * caller and callee.)
2519          * @see #in
2520          *
2521          * @revised 9
2522          */
2523         @Override
2524         public String toString() {
2525             String cname = lookupClass.getName();
2526             if (prevLookupClass != null)
2527                 cname += "/" + prevLookupClass.getName();
2528             switch (allowedModes) {
2529             case 0:  // no privileges
2530                 return cname + "/noaccess";
2531             case UNCONDITIONAL:
2532                 return cname + "/publicLookup";
2533             case PUBLIC:
2534                 return cname + "/public";
2535             case PUBLIC|MODULE:
2536                 return cname + "/module";
2537             case PUBLIC|PACKAGE:
2538             case PUBLIC|MODULE|PACKAGE:
2539                 return cname + "/package";
2540             case PUBLIC|PACKAGE|PRIVATE:
2541             case PUBLIC|MODULE|PACKAGE|PRIVATE:
2542                     return cname + "/private";
2543             case PUBLIC|PACKAGE|PRIVATE|PROTECTED:
2544             case PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED:
2545             case FULL_POWER_MODES:
2546                     return cname;
2547             case TRUSTED:
2548                 return "/trusted";  // internal only; not exported
2549             default:  // Should not happen, but it's a bitfield...
2550                 cname = cname + "/" + Integer.toHexString(allowedModes);
2551                 assert(false) : cname;
2552                 return cname;
2553             }
2554         }
2555 
2556         /**
2557          * Produces a method handle for a static method.
2558          * The type of the method handle will be that of the method.
2559          * (Since static methods do not take receivers, there is no
2560          * additional receiver argument inserted into the method handle type,
2561          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
2562          * The method and all its argument types must be accessible to the lookup object.
2563          * <p>
2564          * The returned method handle will have
2565          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2566          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2567          * <p>
2568          * If the returned method handle is invoked, the method's class will
2569          * be initialized, if it has not already been initialized.
2570          * <p><b>Example:</b>
2571          * <blockquote><pre>{@code
2572 import static java.lang.invoke.MethodHandles.*;
2573 import static java.lang.invoke.MethodType.*;
2574 ...
2575 MethodHandle MH_asList = publicLookup().findStatic(Arrays.class,
2576   "asList", methodType(List.class, Object[].class));
2577 assertEquals("[x, y]", MH_asList.invoke("x", "y").toString());
2578          * }</pre></blockquote>
2579          * @param refc the class from which the method is accessed
2580          * @param name the name of the method
2581          * @param type the type of the method
2582          * @return the desired method handle
2583          * @throws NoSuchMethodException if the method does not exist
2584          * @throws IllegalAccessException if access checking fails,
2585          *                                or if the method is not {@code static},
2586          *                                or if the method's variable arity modifier bit
2587          *                                is set and {@code asVarargsCollector} fails
2588          * @throws    SecurityException if a security manager is present and it
2589          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2590          * @throws NullPointerException if any argument is null
2591          */
2592         public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2593             MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type);
2594             // resolveOrFail could return a non-static <init> method if present
2595             // detect and throw NSME before producing a MethodHandle
2596             if (!method.isStatic() && name.equals("<init>")) {
2597                 throw new NoSuchMethodException("illegal method name: " + name);
2598             }
2599 
2600             return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerLookup(method));
2601         }
2602 
2603         /**
2604          * Produces a method handle for a virtual method.
2605          * The type of the method handle will be that of the method,
2606          * with the receiver type (usually {@code refc}) prepended.
2607          * The method and all its argument types must be accessible to the lookup object.
2608          * <p>
2609          * When called, the handle will treat the first argument as a receiver
2610          * and, for non-private methods, dispatch on the receiver's type to determine which method
2611          * implementation to enter.
2612          * For private methods the named method in {@code refc} will be invoked on the receiver.
2613          * (The dispatching action is identical with that performed by an
2614          * {@code invokevirtual} or {@code invokeinterface} instruction.)
2615          * <p>
2616          * The first argument will be of type {@code refc} if the lookup
2617          * class has full privileges to access the member.  Otherwise
2618          * the member must be {@code protected} and the first argument
2619          * will be restricted in type to the lookup class.
2620          * <p>
2621          * The returned method handle will have
2622          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2623          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2624          * <p>
2625          * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual}
2626          * instructions and method handles produced by {@code findVirtual},
2627          * if the class is {@code MethodHandle} and the name string is
2628          * {@code invokeExact} or {@code invoke}, the resulting
2629          * method handle is equivalent to one produced by
2630          * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or
2631          * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}
2632          * with the same {@code type} argument.
2633          * <p>
2634          * If the class is {@code VarHandle} and the name string corresponds to
2635          * the name of a signature-polymorphic access mode method, the resulting
2636          * method handle is equivalent to one produced by
2637          * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with
2638          * the access mode corresponding to the name string and with the same
2639          * {@code type} arguments.
2640          * <p>
2641          * <b>Example:</b>
2642          * <blockquote><pre>{@code
2643 import static java.lang.invoke.MethodHandles.*;
2644 import static java.lang.invoke.MethodType.*;
2645 ...
2646 MethodHandle MH_concat = publicLookup().findVirtual(String.class,
2647   "concat", methodType(String.class, String.class));
2648 MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class,
2649   "hashCode", methodType(int.class));
2650 MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class,
2651   "hashCode", methodType(int.class));
2652 assertEquals("xy", (String) MH_concat.invokeExact("x", "y"));
2653 assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy"));
2654 assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy"));
2655 // interface method:
2656 MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class,
2657   "subSequence", methodType(CharSequence.class, int.class, int.class));
2658 assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString());
2659 // constructor "internal method" must be accessed differently:
2660 MethodType MT_newString = methodType(void.class); //()V for new String()
2661 try { assertEquals("impossible", lookup()
2662         .findVirtual(String.class, "<init>", MT_newString));
2663  } catch (NoSuchMethodException ex) { } // OK
2664 MethodHandle MH_newString = publicLookup()
2665   .findConstructor(String.class, MT_newString);
2666 assertEquals("", (String) MH_newString.invokeExact());
2667          * }</pre></blockquote>
2668          *
2669          * @param refc the class or interface from which the method is accessed
2670          * @param name the name of the method
2671          * @param type the type of the method, with the receiver argument omitted
2672          * @return the desired method handle
2673          * @throws NoSuchMethodException if the method does not exist
2674          * @throws IllegalAccessException if access checking fails,
2675          *                                or if the method is {@code static},
2676          *                                or if the method's variable arity modifier bit
2677          *                                is set and {@code asVarargsCollector} fails
2678          * @throws    SecurityException if a security manager is present and it
2679          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2680          * @throws NullPointerException if any argument is null
2681          */
2682         public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2683             if (refc == MethodHandle.class) {
2684                 MethodHandle mh = findVirtualForMH(name, type);
2685                 if (mh != null)  return mh;
2686             } else if (refc == VarHandle.class) {
2687                 MethodHandle mh = findVirtualForVH(name, type);
2688                 if (mh != null)  return mh;
2689             }
2690             byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual);
2691             MemberName method = resolveOrFail(refKind, refc, name, type);
2692             return getDirectMethod(refKind, refc, method, findBoundCallerLookup(method));
2693         }
2694         private MethodHandle findVirtualForMH(String name, MethodType type) {
2695             // these names require special lookups because of the implicit MethodType argument
2696             if ("invoke".equals(name))
2697                 return invoker(type);
2698             if ("invokeExact".equals(name))
2699                 return exactInvoker(type);
2700             assert(!MemberName.isMethodHandleInvokeName(name));
2701             return null;
2702         }
2703         private MethodHandle findVirtualForVH(String name, MethodType type) {
2704             try {
2705                 return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type);
2706             } catch (IllegalArgumentException e) {
2707                 return null;
2708             }
2709         }
2710 
2711         /**
2712          * Produces a method handle which creates an object and initializes it, using
2713          * the constructor of the specified type.
2714          * The parameter types of the method handle will be those of the constructor,
2715          * while the return type will be a reference to the constructor's class.
2716          * The constructor and all its argument types must be accessible to the lookup object.
2717          * <p>
2718          * The requested type must have a return type of {@code void}.
2719          * (This is consistent with the JVM's treatment of constructor type descriptors.)
2720          * <p>
2721          * The returned method handle will have
2722          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2723          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
2724          * <p>
2725          * If the returned method handle is invoked, the constructor's class will
2726          * be initialized, if it has not already been initialized.
2727          * <p><b>Example:</b>
2728          * <blockquote><pre>{@code
2729 import static java.lang.invoke.MethodHandles.*;
2730 import static java.lang.invoke.MethodType.*;
2731 ...
2732 MethodHandle MH_newArrayList = publicLookup().findConstructor(
2733   ArrayList.class, methodType(void.class, Collection.class));
2734 Collection orig = Arrays.asList("x", "y");
2735 Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig);
2736 assert(orig != copy);
2737 assertEquals(orig, copy);
2738 // a variable-arity constructor:
2739 MethodHandle MH_newProcessBuilder = publicLookup().findConstructor(
2740   ProcessBuilder.class, methodType(void.class, String[].class));
2741 ProcessBuilder pb = (ProcessBuilder)
2742   MH_newProcessBuilder.invoke("x", "y", "z");
2743 assertEquals("[x, y, z]", pb.command().toString());
2744          * }</pre></blockquote>
2745          *
2746          * @apiNote
2747          * This method does not find a static {@code <init>} factory method as it is invoked
2748          * via {@code invokestatic} bytecode as opposed to {@code invokespecial} for an
2749          * object constructor.  To look up static {@code <init>} factory method, use
2750          * the {@link #findStatic(Class, String, MethodType) findStatic} method.
2751          *
2752          * @param refc the class or interface from which the method is accessed
2753          * @param type the type of the method, with the receiver argument omitted, and a void return type
2754          * @return the desired method handle
2755          * @throws NoSuchMethodException if the constructor does not exist
2756          * @throws IllegalAccessException if access checking fails
2757          *                                or if the method's variable arity modifier bit
2758          *                                is set and {@code asVarargsCollector} fails
2759          * @throws    SecurityException if a security manager is present and it
2760          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2761          * @throws NullPointerException if any argument is null
2762          */
2763         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
2764             if (refc.isArray()) {
2765                 throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
2766             }
2767             if (type.returnType() != void.class) {
2768                 throw new NoSuchMethodException("Constructors must have void return type: " + refc.getName());
2769             }
2770             String name = "<init>";
2771             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
2772             return getDirectConstructor(refc, ctor);
2773         }
2774 
2775         /**
2776          * Looks up a class by name from the lookup context defined by this {@code Lookup} object,
2777          * <a href="MethodHandles.Lookup.html#equiv">as if resolved</a> by an {@code ldc} instruction.
2778          * Such a resolution, as specified in JVMS {@jvms 5.4.3.1}, attempts to locate and load the class,
2779          * and then determines whether the class is accessible to this lookup object.
2780          * <p>
2781          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class},
2782          * its class loader, and the {@linkplain #lookupModes() lookup modes}.
2783          *
2784          * @param targetName the fully qualified name of the class to be looked up.
2785          * @return the requested class.
2786          * @throws SecurityException if a security manager is present and it
2787          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2788          * @throws LinkageError if the linkage fails
2789          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
2790          * @throws IllegalAccessException if the class is not accessible, using the allowed access
2791          * modes.
2792          * @throws NullPointerException if {@code targetName} is null
2793          * @since 9
2794          * @jvms 5.4.3.1 Class and Interface Resolution
2795          */
2796         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
2797             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
2798             return accessClass(targetClass);
2799         }
2800 
2801         /**
2802          * Ensures that {@code targetClass} has been initialized. The class
2803          * to be initialized must be {@linkplain #accessClass accessible}
2804          * to this {@code Lookup} object.  This method causes {@code targetClass}
2805          * to be initialized if it has not been already initialized,
2806          * as specified in JVMS {@jvms 5.5}.
2807          *
2808          * <p>
2809          * This method returns when {@code targetClass} is fully initialized, or
2810          * when {@code targetClass} is being initialized by the current thread.
2811          *
2812          * @param targetClass the class to be initialized
2813          * @return {@code targetClass} that has been initialized, or that is being
2814          *         initialized by the current thread.
2815          *
2816          * @throws  IllegalArgumentException if {@code targetClass} is a primitive type or {@code void}
2817          *          or array class
2818          * @throws  IllegalAccessException if {@code targetClass} is not
2819          *          {@linkplain #accessClass accessible} to this lookup
2820          * @throws  ExceptionInInitializerError if the class initialization provoked
2821          *          by this method fails
2822          * @throws  SecurityException if a security manager is present and it
2823          *          <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2824          * @since 15
2825          * @jvms 5.5 Initialization
2826          */
2827         public Class<?> ensureInitialized(Class<?> targetClass) throws IllegalAccessException {
2828             if (targetClass.isPrimitive())
2829                 throw new IllegalArgumentException(targetClass + " is a primitive class");
2830             if (targetClass.isArray())
2831                 throw new IllegalArgumentException(targetClass + " is an array class");
2832 
2833             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2834                 throw makeAccessException(targetClass);
2835             }
2836             checkSecurityManager(targetClass);
2837 
2838             // ensure class initialization
2839             Unsafe.getUnsafe().ensureClassInitialized(targetClass);
2840             return targetClass;
2841         }
2842 
2843         /*
2844          * Returns IllegalAccessException due to access violation to the given targetClass.
2845          *
2846          * This method is called by {@link Lookup#accessClass} and {@link Lookup#ensureInitialized}
2847          * which verifies access to a class rather a member.
2848          */
2849         private IllegalAccessException makeAccessException(Class<?> targetClass) {
2850             String message = "access violation: "+ targetClass;
2851             if (this == MethodHandles.publicLookup()) {
2852                 message += ", from public Lookup";
2853             } else {
2854                 Module m = lookupClass().getModule();
2855                 message += ", from " + lookupClass() + " (" + m + ")";
2856                 if (prevLookupClass != null) {
2857                     message += ", previous lookup " +
2858                             prevLookupClass.getName() + " (" + prevLookupClass.getModule() + ")";
2859                 }
2860             }
2861             return new IllegalAccessException(message);
2862         }
2863 
2864         /**
2865          * Determines if a class can be accessed from the lookup context defined by
2866          * this {@code Lookup} object. The static initializer of the class is not run.
2867          * If {@code targetClass} is an array class, {@code targetClass} is accessible
2868          * if the element type of the array class is accessible.  Otherwise,
2869          * {@code targetClass} is determined as accessible as follows.
2870          *
2871          * <p>
2872          * If {@code targetClass} is in the same module as the lookup class,
2873          * the lookup class is {@code LC} in module {@code M1} and
2874          * the previous lookup class is in module {@code M0} or
2875          * {@code null} if not present,
2876          * {@code targetClass} is accessible if and only if one of the following is true:
2877          * <ul>
2878          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
2879          *     {@code LC} or other class in the same nest of {@code LC}.</li>
2880          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
2881          *     in the same runtime package of {@code LC}.</li>
2882          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
2883          *     a public type in {@code M1}.</li>
2884          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
2885          *     a public type in a package exported by {@code M1} to at least  {@code M0}
2886          *     if the previous lookup class is present; otherwise, {@code targetClass}
2887          *     is a public type in a package exported by {@code M1} unconditionally.</li>
2888          * </ul>
2889          *
2890          * <p>
2891          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
2892          * can access public types in all modules when the type is in a package
2893          * that is exported unconditionally.
2894          * <p>
2895          * Otherwise, {@code targetClass} is in a different module from {@code lookupClass},
2896          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
2897          * is inaccessible.
2898          * <p>
2899          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
2900          * {@code M1} is the module containing {@code lookupClass} and
2901          * {@code M2} is the module containing {@code targetClass},
2902          * then {@code targetClass} is accessible if and only if
2903          * <ul>
2904          * <li>{@code M1} reads {@code M2}, and
2905          * <li>{@code targetClass} is public and in a package exported by
2906          *     {@code M2} at least to {@code M1}.
2907          * </ul>
2908          * <p>
2909          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
2910          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
2911          * containing the previous lookup class, then {@code targetClass} is accessible
2912          * if and only if one of the following is true:
2913          * <ul>
2914          * <li>{@code targetClass} is in {@code M0} and {@code M1}
2915          *     {@linkplain Module#reads reads} {@code M0} and the type is
2916          *     in a package that is exported to at least {@code M1}.
2917          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2918          *     {@linkplain Module#reads reads} {@code M1} and the type is
2919          *     in a package that is exported to at least {@code M0}.
2920          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2921          *     and {@code M1} reads {@code M2} and the type is in a package
2922          *     that is exported to at least both {@code M0} and {@code M2}.
2923          * </ul>
2924          * <p>
2925          * Otherwise, {@code targetClass} is not accessible.
2926          *
2927          * @param targetClass the class to be access-checked
2928          * @return the class that has been access-checked
2929          * @throws IllegalAccessException if the class is not accessible from the lookup class
2930          * and previous lookup class, if present, using the allowed access modes.
2931          * @throws SecurityException if a security manager is present and it
2932          *                           <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2933          * @throws NullPointerException if {@code targetClass} is {@code null}
2934          * @since 9
2935          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2936          */
2937         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2938             if (!isClassAccessible(targetClass)) {
2939                 throw makeAccessException(targetClass);
2940             }
2941             checkSecurityManager(targetClass);
2942             return targetClass;
2943         }
2944 
2945         /**
2946          * Produces an early-bound method handle for a virtual method.
2947          * It will bypass checks for overriding methods on the receiver,
2948          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2949          * instruction from within the explicitly specified {@code specialCaller}.
2950          * The type of the method handle will be that of the method,
2951          * with a suitably restricted receiver type prepended.
2952          * (The receiver type will be {@code specialCaller} or a subtype.)
2953          * The method and all its argument types must be accessible
2954          * to the lookup object.
2955          * <p>
2956          * Before method resolution,
2957          * if the explicitly specified caller class is not identical with the
2958          * lookup class, or if this lookup object does not have
2959          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
2960          * privileges, the access fails.
2961          * <p>
2962          * The returned method handle will have
2963          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
2964          * the method's variable arity modifier bit ({@code 0x0080}) is set.
2965          * <p style="font-size:smaller;">
2966          * <em>(Note:  JVM internal methods named {@code "<init>"} are not visible to this API,
2967          * even though the {@code invokespecial} instruction can refer to them
2968          * in special circumstances.  Use {@link #findConstructor findConstructor}
2969          * to access instance initialization methods in a safe manner.)</em>
2970          * <p><b>Example:</b>
2971          * <blockquote><pre>{@code
2972 import static java.lang.invoke.MethodHandles.*;
2973 import static java.lang.invoke.MethodType.*;
2974 ...
2975 static class Listie extends ArrayList {
2976   public String toString() { return "[wee Listie]"; }
2977   static Lookup lookup() { return MethodHandles.lookup(); }
2978 }
2979 ...
2980 // no access to constructor via invokeSpecial:
2981 MethodHandle MH_newListie = Listie.lookup()
2982   .findConstructor(Listie.class, methodType(void.class));
2983 Listie l = (Listie) MH_newListie.invokeExact();
2984 try { assertEquals("impossible", Listie.lookup().findSpecial(
2985         Listie.class, "<init>", methodType(void.class), Listie.class));
2986  } catch (NoSuchMethodException ex) { } // OK
2987 // access to super and self methods via invokeSpecial:
2988 MethodHandle MH_super = Listie.lookup().findSpecial(
2989   ArrayList.class, "toString" , methodType(String.class), Listie.class);
2990 MethodHandle MH_this = Listie.lookup().findSpecial(
2991   Listie.class, "toString" , methodType(String.class), Listie.class);
2992 MethodHandle MH_duper = Listie.lookup().findSpecial(
2993   Object.class, "toString" , methodType(String.class), Listie.class);
2994 assertEquals("[]", (String) MH_super.invokeExact(l));
2995 assertEquals(""+l, (String) MH_this.invokeExact(l));
2996 assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method
2997 try { assertEquals("inaccessible", Listie.lookup().findSpecial(
2998         String.class, "toString", methodType(String.class), Listie.class));
2999  } catch (IllegalAccessException ex) { } // OK
3000 Listie subl = new Listie() { public String toString() { return "[subclass]"; } };
3001 assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method
3002          * }</pre></blockquote>
3003          *
3004          * @param refc the class or interface from which the method is accessed
3005          * @param name the name of the method (which must not be "&lt;init&gt;")
3006          * @param type the type of the method, with the receiver argument omitted
3007          * @param specialCaller the proposed calling class to perform the {@code invokespecial}
3008          * @return the desired method handle
3009          * @throws NoSuchMethodException if the method does not exist
3010          * @throws IllegalAccessException if access checking fails,
3011          *                                or if the method is {@code static},
3012          *                                or if the method's variable arity modifier bit
3013          *                                is set and {@code asVarargsCollector} fails
3014          * @throws    SecurityException if a security manager is present and it
3015          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3016          * @throws NullPointerException if any argument is null
3017          */
3018         public MethodHandle findSpecial(Class<?> refc, String name, MethodType type,
3019                                         Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException {
3020             checkSpecialCaller(specialCaller, refc);
3021             Lookup specialLookup = this.in(specialCaller);
3022             MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type);
3023             return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerLookup(method));
3024         }
3025 
3026         /**
3027          * Produces a method handle giving read access to a non-static field.
3028          * The type of the method handle will have a return type of the field's
3029          * value type.
3030          * The method handle's single argument will be the instance containing
3031          * the field.
3032          * Access checking is performed immediately on behalf of the lookup class.
3033          * @param refc the class or interface from which the method is accessed
3034          * @param name the field's name
3035          * @param type the field's type
3036          * @return a method handle which can load values from the field
3037          * @throws NoSuchFieldException if the field does not exist
3038          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3039          * @throws    SecurityException if a security manager is present and it
3040          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3041          * @throws NullPointerException if any argument is null
3042          * @see #findVarHandle(Class, String, Class)
3043          */
3044         public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3045             MemberName field = resolveOrFail(REF_getField, refc, name, type);
3046             return getDirectField(REF_getField, refc, field);
3047         }
3048 
3049         /**
3050          * Produces a method handle giving write access to a non-static field.
3051          * The type of the method handle will have a void return type.
3052          * The method handle will take two arguments, the instance containing
3053          * the field, and the value to be stored.
3054          * The second argument will be of the field's value type.
3055          * Access checking is performed immediately on behalf of the lookup class.
3056          * @param refc the class or interface from which the method is accessed
3057          * @param name the field's name
3058          * @param type the field's type
3059          * @return a method handle which can store values into the field
3060          * @throws NoSuchFieldException if the field does not exist
3061          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3062          *                                or {@code final}
3063          * @throws    SecurityException if a security manager is present and it
3064          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3065          * @throws NullPointerException if any argument is null
3066          * @see #findVarHandle(Class, String, Class)
3067          */
3068         public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3069             MemberName field = resolveOrFail(REF_putField, refc, name, type);
3070             return getDirectField(REF_putField, refc, field);
3071         }
3072 
3073         /**
3074          * Produces a VarHandle giving access to a non-static field {@code name}
3075          * of type {@code type} declared in a class of type {@code recv}.
3076          * The VarHandle's variable type is {@code type} and it has one
3077          * coordinate type, {@code recv}.
3078          * <p>
3079          * Access checking is performed immediately on behalf of the lookup
3080          * class.
3081          * <p>
3082          * Certain access modes of the returned VarHandle are unsupported under
3083          * the following conditions:
3084          * <ul>
3085          * <li>if the field is declared {@code final}, then the write, atomic
3086          *     update, numeric atomic update, and bitwise atomic update access
3087          *     modes are unsupported.
3088          * <li>if the field type is anything other than {@code byte},
3089          *     {@code short}, {@code char}, {@code int}, {@code long},
3090          *     {@code float}, or {@code double} then numeric atomic update
3091          *     access modes are unsupported.
3092          * <li>if the field type is anything other than {@code boolean},
3093          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3094          *     {@code long} then bitwise atomic update access modes are
3095          *     unsupported.
3096          * </ul>
3097          * <p>
3098          * If the field is declared {@code volatile} then the returned VarHandle
3099          * will override access to the field (effectively ignore the
3100          * {@code volatile} declaration) in accordance to its specified
3101          * access modes.
3102          * <p>
3103          * If the field type is {@code float} or {@code double} then numeric
3104          * and atomic update access modes compare values using their bitwise
3105          * representation (see {@link Float#floatToRawIntBits} and
3106          * {@link Double#doubleToRawLongBits}, respectively).
3107          * @apiNote
3108          * Bitwise comparison of {@code float} values or {@code double} values,
3109          * as performed by the numeric and atomic update access modes, differ
3110          * from the primitive {@code ==} operator and the {@link Float#equals}
3111          * and {@link Double#equals} methods, specifically with respect to
3112          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3113          * Care should be taken when performing a compare and set or a compare
3114          * and exchange operation with such values since the operation may
3115          * unexpectedly fail.
3116          * There are many possible NaN values that are considered to be
3117          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3118          * provided by Java can distinguish between them.  Operation failure can
3119          * occur if the expected or witness value is a NaN value and it is
3120          * transformed (perhaps in a platform specific manner) into another NaN
3121          * value, and thus has a different bitwise representation (see
3122          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3123          * details).
3124          * The values {@code -0.0} and {@code +0.0} have different bitwise
3125          * representations but are considered equal when using the primitive
3126          * {@code ==} operator.  Operation failure can occur if, for example, a
3127          * numeric algorithm computes an expected value to be say {@code -0.0}
3128          * and previously computed the witness value to be say {@code +0.0}.
3129          * @param recv the receiver class, of type {@code R}, that declares the
3130          * non-static field
3131          * @param name the field's name
3132          * @param type the field's type, of type {@code T}
3133          * @return a VarHandle giving access to non-static fields.
3134          * @throws NoSuchFieldException if the field does not exist
3135          * @throws IllegalAccessException if access checking fails, or if the field is {@code static}
3136          * @throws    SecurityException if a security manager is present and it
3137          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3138          * @throws NullPointerException if any argument is null
3139          * @since 9
3140          */
3141         public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3142             MemberName getField = resolveOrFail(REF_getField, recv, name, type);
3143             MemberName putField = resolveOrFail(REF_putField, recv, name, type);
3144             return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField);
3145         }
3146 
3147         /**
3148          * Produces a method handle giving read access to a static field.
3149          * The type of the method handle will have a return type of the field's
3150          * value type.
3151          * The method handle will take no arguments.
3152          * Access checking is performed immediately on behalf of the lookup class.
3153          * <p>
3154          * If the returned method handle is invoked, the field's class will
3155          * be initialized, if it has not already been initialized.
3156          * @param refc the class or interface from which the method is accessed
3157          * @param name the field's name
3158          * @param type the field's type
3159          * @return a method handle which can load values from the field
3160          * @throws NoSuchFieldException if the field does not exist
3161          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3162          * @throws    SecurityException if a security manager is present and it
3163          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3164          * @throws NullPointerException if any argument is null
3165          */
3166         public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3167             MemberName field = resolveOrFail(REF_getStatic, refc, name, type);
3168             return getDirectField(REF_getStatic, refc, field);
3169         }
3170 
3171         /**
3172          * Produces a method handle giving write access to a static field.
3173          * The type of the method handle will have a void return type.
3174          * The method handle will take a single
3175          * argument, of the field's value type, the value to be stored.
3176          * Access checking is performed immediately on behalf of the lookup class.
3177          * <p>
3178          * If the returned method handle is invoked, the field's class will
3179          * be initialized, if it has not already been initialized.
3180          * @param refc the class or interface from which the method is accessed
3181          * @param name the field's name
3182          * @param type the field's type
3183          * @return a method handle which can store values into the field
3184          * @throws NoSuchFieldException if the field does not exist
3185          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3186          *                                or is {@code final}
3187          * @throws    SecurityException if a security manager is present and it
3188          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3189          * @throws NullPointerException if any argument is null
3190          */
3191         public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3192             MemberName field = resolveOrFail(REF_putStatic, refc, name, type);
3193             return getDirectField(REF_putStatic, refc, field);
3194         }
3195 
3196         /**
3197          * Produces a VarHandle giving access to a static field {@code name} of
3198          * type {@code type} declared in a class of type {@code decl}.
3199          * The VarHandle's variable type is {@code type} and it has no
3200          * coordinate types.
3201          * <p>
3202          * Access checking is performed immediately on behalf of the lookup
3203          * class.
3204          * <p>
3205          * If the returned VarHandle is operated on, the declaring class will be
3206          * initialized, if it has not already been initialized.
3207          * <p>
3208          * Certain access modes of the returned VarHandle are unsupported under
3209          * the following conditions:
3210          * <ul>
3211          * <li>if the field is declared {@code final}, then the write, atomic
3212          *     update, numeric atomic update, and bitwise atomic update access
3213          *     modes are unsupported.
3214          * <li>if the field type is anything other than {@code byte},
3215          *     {@code short}, {@code char}, {@code int}, {@code long},
3216          *     {@code float}, or {@code double}, then numeric atomic update
3217          *     access modes are unsupported.
3218          * <li>if the field type is anything other than {@code boolean},
3219          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3220          *     {@code long} then bitwise atomic update access modes are
3221          *     unsupported.
3222          * </ul>
3223          * <p>
3224          * If the field is declared {@code volatile} then the returned VarHandle
3225          * will override access to the field (effectively ignore the
3226          * {@code volatile} declaration) in accordance to its specified
3227          * access modes.
3228          * <p>
3229          * If the field type is {@code float} or {@code double} then numeric
3230          * and atomic update access modes compare values using their bitwise
3231          * representation (see {@link Float#floatToRawIntBits} and
3232          * {@link Double#doubleToRawLongBits}, respectively).
3233          * @apiNote
3234          * Bitwise comparison of {@code float} values or {@code double} values,
3235          * as performed by the numeric and atomic update access modes, differ
3236          * from the primitive {@code ==} operator and the {@link Float#equals}
3237          * and {@link Double#equals} methods, specifically with respect to
3238          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3239          * Care should be taken when performing a compare and set or a compare
3240          * and exchange operation with such values since the operation may
3241          * unexpectedly fail.
3242          * There are many possible NaN values that are considered to be
3243          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3244          * provided by Java can distinguish between them.  Operation failure can
3245          * occur if the expected or witness value is a NaN value and it is
3246          * transformed (perhaps in a platform specific manner) into another NaN
3247          * value, and thus has a different bitwise representation (see
3248          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3249          * details).
3250          * The values {@code -0.0} and {@code +0.0} have different bitwise
3251          * representations but are considered equal when using the primitive
3252          * {@code ==} operator.  Operation failure can occur if, for example, a
3253          * numeric algorithm computes an expected value to be say {@code -0.0}
3254          * and previously computed the witness value to be say {@code +0.0}.
3255          * @param decl the class that declares the static field
3256          * @param name the field's name
3257          * @param type the field's type, of type {@code T}
3258          * @return a VarHandle giving access to a static field
3259          * @throws NoSuchFieldException if the field does not exist
3260          * @throws IllegalAccessException if access checking fails, or if the field is not {@code static}
3261          * @throws    SecurityException if a security manager is present and it
3262          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3263          * @throws NullPointerException if any argument is null
3264          * @since 9
3265          */
3266         public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3267             MemberName getField = resolveOrFail(REF_getStatic, decl, name, type);
3268             MemberName putField = resolveOrFail(REF_putStatic, decl, name, type);
3269             return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField);
3270         }
3271 
3272         /**
3273          * Produces an early-bound method handle for a non-static method.
3274          * The receiver must have a supertype {@code defc} in which a method
3275          * of the given name and type is accessible to the lookup class.
3276          * The method and all its argument types must be accessible to the lookup object.
3277          * The type of the method handle will be that of the method,
3278          * without any insertion of an additional receiver parameter.
3279          * The given receiver will be bound into the method handle,
3280          * so that every call to the method handle will invoke the
3281          * requested method on the given receiver.
3282          * <p>
3283          * The returned method handle will have
3284          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3285          * the method's variable arity modifier bit ({@code 0x0080}) is set
3286          * <em>and</em> the trailing array argument is not the only argument.
3287          * (If the trailing array argument is the only argument,
3288          * the given receiver value will be bound to it.)
3289          * <p>
3290          * This is almost equivalent to the following code, with some differences noted below:
3291          * <blockquote><pre>{@code
3292 import static java.lang.invoke.MethodHandles.*;
3293 import static java.lang.invoke.MethodType.*;
3294 ...
3295 MethodHandle mh0 = lookup().findVirtual(defc, name, type);
3296 MethodHandle mh1 = mh0.bindTo(receiver);
3297 mh1 = mh1.withVarargs(mh0.isVarargsCollector());
3298 return mh1;
3299          * }</pre></blockquote>
3300          * where {@code defc} is either {@code receiver.getClass()} or a super
3301          * type of that class, in which the requested method is accessible
3302          * to the lookup class.
3303          * (Unlike {@code bind}, {@code bindTo} does not preserve variable arity.
3304          * Also, {@code bindTo} may throw a {@code ClassCastException} in instances where {@code bind} would
3305          * throw an {@code IllegalAccessException}, as in the case where the member is {@code protected} and
3306          * the receiver is restricted by {@code findVirtual} to the lookup class.)
3307          * @param receiver the object from which the method is accessed
3308          * @param name the name of the method
3309          * @param type the type of the method, with the receiver argument omitted
3310          * @return the desired method handle
3311          * @throws NoSuchMethodException if the method does not exist
3312          * @throws IllegalAccessException if access checking fails
3313          *                                or if the method's variable arity modifier bit
3314          *                                is set and {@code asVarargsCollector} fails
3315          * @throws    SecurityException if a security manager is present and it
3316          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3317          * @throws NullPointerException if any argument is null
3318          * @see MethodHandle#bindTo
3319          * @see #findVirtual
3320          */
3321         public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3322             Class<? extends Object> refc = receiver.getClass(); // may get NPE
3323             MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type);
3324             MethodHandle mh = getDirectMethodNoRestrictInvokeSpecial(refc, method, findBoundCallerLookup(method));
3325             if (!mh.type().leadingReferenceParameter().isAssignableFrom(receiver.getClass())) {
3326                 throw new IllegalAccessException("The restricted defining class " +
3327                                                  mh.type().leadingReferenceParameter().getName() +
3328                                                  " is not assignable from receiver class " +
3329                                                  receiver.getClass().getName());
3330             }
3331             return mh.bindArgumentL(0, receiver).setVarargs(method);
3332         }
3333 
3334         /**
3335          * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3336          * to <i>m</i>, if the lookup class has permission.
3337          * If <i>m</i> is non-static, the receiver argument is treated as an initial argument.
3338          * If <i>m</i> is virtual, overriding is respected on every call.
3339          * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped.
3340          * The type of the method handle will be that of the method,
3341          * with the receiver type prepended (but only if it is non-static).
3342          * If the method's {@code accessible} flag is not set,
3343          * access checking is performed immediately on behalf of the lookup class.
3344          * If <i>m</i> is not public, do not share the resulting handle with untrusted parties.
3345          * <p>
3346          * The returned method handle will have
3347          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3348          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3349          * <p>
3350          * If <i>m</i> is static, and
3351          * if the returned method handle is invoked, the method's class will
3352          * be initialized, if it has not already been initialized.
3353          * @param m the reflected method
3354          * @return a method handle which can invoke the reflected method
3355          * @throws IllegalAccessException if access checking fails
3356          *                                or if the method's variable arity modifier bit
3357          *                                is set and {@code asVarargsCollector} fails
3358          * @throws NullPointerException if the argument is null
3359          */
3360         public MethodHandle unreflect(Method m) throws IllegalAccessException {
3361             if (m.getDeclaringClass() == MethodHandle.class) {
3362                 MethodHandle mh = unreflectForMH(m);
3363                 if (mh != null)  return mh;
3364             }
3365             if (m.getDeclaringClass() == VarHandle.class) {
3366                 MethodHandle mh = unreflectForVH(m);
3367                 if (mh != null)  return mh;
3368             }
3369             MemberName method = new MemberName(m);
3370             byte refKind = method.getReferenceKind();
3371             if (refKind == REF_invokeSpecial)
3372                 refKind = REF_invokeVirtual;
3373             assert(method.isMethod());
3374             @SuppressWarnings("deprecation")
3375             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
3376             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3377         }
3378         private MethodHandle unreflectForMH(Method m) {
3379             // these names require special lookups because they throw UnsupportedOperationException
3380             if (MemberName.isMethodHandleInvokeName(m.getName()))
3381                 return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m));
3382             return null;
3383         }
3384         private MethodHandle unreflectForVH(Method m) {
3385             // these names require special lookups because they throw UnsupportedOperationException
3386             if (MemberName.isVarHandleMethodInvokeName(m.getName()))
3387                 return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m));
3388             return null;
3389         }
3390 
3391         /**
3392          * Produces a method handle for a reflected method.
3393          * It will bypass checks for overriding methods on the receiver,
3394          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
3395          * instruction from within the explicitly specified {@code specialCaller}.
3396          * The type of the method handle will be that of the method,
3397          * with a suitably restricted receiver type prepended.
3398          * (The receiver type will be {@code specialCaller} or a subtype.)
3399          * If the method's {@code accessible} flag is not set,
3400          * access checking is performed immediately on behalf of the lookup class,
3401          * as if {@code invokespecial} instruction were being linked.
3402          * <p>
3403          * Before method resolution,
3404          * if the explicitly specified caller class is not identical with the
3405          * lookup class, or if this lookup object does not have
3406          * <a href="MethodHandles.Lookup.html#privacc">private access</a>
3407          * privileges, the access fails.
3408          * <p>
3409          * The returned method handle will have
3410          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3411          * the method's variable arity modifier bit ({@code 0x0080}) is set.
3412          * @param m the reflected method
3413          * @param specialCaller the class nominally calling the method
3414          * @return a method handle which can invoke the reflected method
3415          * @throws IllegalAccessException if access checking fails,
3416          *                                or if the method is {@code static},
3417          *                                or if the method's variable arity modifier bit
3418          *                                is set and {@code asVarargsCollector} fails
3419          * @throws NullPointerException if any argument is null
3420          */
3421         public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException {
3422             checkSpecialCaller(specialCaller, m.getDeclaringClass());
3423             Lookup specialLookup = this.in(specialCaller);
3424             MemberName method = new MemberName(m, true);
3425             assert(method.isMethod());
3426             // ignore m.isAccessible:  this is a new kind of access
3427             return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerLookup(method));
3428         }
3429 
3430         /**
3431          * Produces a method handle for a reflected constructor.
3432          * The type of the method handle will be that of the constructor,
3433          * with the return type changed to the declaring class.
3434          * The method handle will perform a {@code newInstance} operation,
3435          * creating a new instance of the constructor's class on the
3436          * arguments passed to the method handle.
3437          * <p>
3438          * If the constructor's {@code accessible} flag is not set,
3439          * access checking is performed immediately on behalf of the lookup class.
3440          * <p>
3441          * The returned method handle will have
3442          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if
3443          * the constructor's variable arity modifier bit ({@code 0x0080}) is set.
3444          * <p>
3445          * If the returned method handle is invoked, the constructor's class will
3446          * be initialized, if it has not already been initialized.
3447          * @param c the reflected constructor
3448          * @return a method handle which can invoke the reflected constructor
3449          * @throws IllegalAccessException if access checking fails
3450          *                                or if the method's variable arity modifier bit
3451          *                                is set and {@code asVarargsCollector} fails
3452          * @throws NullPointerException if the argument is null
3453          */
3454         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
3455             MemberName ctor = new MemberName(c);
3456             assert(ctor.isObjectConstructorOrStaticInitMethod());
3457             @SuppressWarnings("deprecation")
3458             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
3459             Class<?> defc = c.getDeclaringClass();
3460             if (ctor.isObjectConstructor()) {
3461                 assert(ctor.getReturnType() == void.class);
3462                 return lookup.getDirectConstructorNoSecurityManager(defc, ctor);
3463             } else {
3464                 // static init factory is a static method
3465                 assert(ctor.isMethod() && ctor.getReturnType() == defc && ctor.getReferenceKind() == REF_invokeStatic) : ctor.toString();
3466                 assert(!MethodHandleNatives.isCallerSensitive(ctor));  // must not be caller-sensitive
3467                 return lookup.getDirectMethodNoSecurityManager(ctor.getReferenceKind(), defc, ctor, lookup);
3468             }
3469         }
3470 
3471         /**
3472          * Produces a method handle giving read access to a reflected field.
3473          * The type of the method handle will have a return type of the field's
3474          * value type.
3475          * If the field is {@code static}, the method handle will take no arguments.
3476          * Otherwise, its single argument will be the instance containing
3477          * the field.
3478          * If the {@code Field} object's {@code accessible} flag is not set,
3479          * access checking is performed immediately on behalf of the lookup class.
3480          * <p>
3481          * If the field is static, and
3482          * if the returned method handle is invoked, the field's class will
3483          * be initialized, if it has not already been initialized.
3484          * @param f the reflected field
3485          * @return a method handle which can load values from the reflected field
3486          * @throws IllegalAccessException if access checking fails
3487          * @throws NullPointerException if the argument is null
3488          */
3489         public MethodHandle unreflectGetter(Field f) throws IllegalAccessException {
3490             return unreflectField(f, false);
3491         }
3492 
3493         /**
3494          * Produces a method handle giving write access to a reflected field.
3495          * The type of the method handle will have a void return type.
3496          * If the field is {@code static}, the method handle will take a single
3497          * argument, of the field's value type, the value to be stored.
3498          * Otherwise, the two arguments will be the instance containing
3499          * the field, and the value to be stored.
3500          * If the {@code Field} object's {@code accessible} flag is not set,
3501          * access checking is performed immediately on behalf of the lookup class.
3502          * <p>
3503          * If the field is {@code final}, write access will not be
3504          * allowed and access checking will fail, except under certain
3505          * narrow circumstances documented for {@link Field#set Field.set}.
3506          * A method handle is returned only if a corresponding call to
3507          * the {@code Field} object's {@code set} method could return
3508          * normally.  In particular, fields which are both {@code static}
3509          * and {@code final} may never be set.
3510          * <p>
3511          * If the field is {@code static}, and
3512          * if the returned method handle is invoked, the field's class will
3513          * be initialized, if it has not already been initialized.
3514          * @param f the reflected field
3515          * @return a method handle which can store values into the reflected field
3516          * @throws IllegalAccessException if access checking fails,
3517          *         or if the field is {@code final} and write access
3518          *         is not enabled on the {@code Field} object
3519          * @throws NullPointerException if the argument is null
3520          */
3521         public MethodHandle unreflectSetter(Field f) throws IllegalAccessException {
3522             return unreflectField(f, true);
3523         }
3524 
3525         private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException {
3526             MemberName field = new MemberName(f, isSetter);
3527             if (isSetter && field.isFinal()) {
3528                 if (field.isTrustedFinalField()) {
3529                     String msg = field.isStatic() ? "static final field has no write access"
3530                                                   : "final field has no write access";
3531                     throw field.makeAccessException(msg, this);
3532                 }
3533             }
3534             assert(isSetter
3535                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
3536                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
3537             @SuppressWarnings("deprecation")
3538             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
3539             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
3540         }
3541 
3542         /**
3543          * Produces a VarHandle giving access to a reflected field {@code f}
3544          * of type {@code T} declared in a class of type {@code R}.
3545          * The VarHandle's variable type is {@code T}.
3546          * If the field is non-static the VarHandle has one coordinate type,
3547          * {@code R}.  Otherwise, the field is static, and the VarHandle has no
3548          * coordinate types.
3549          * <p>
3550          * Access checking is performed immediately on behalf of the lookup
3551          * class, regardless of the value of the field's {@code accessible}
3552          * flag.
3553          * <p>
3554          * If the field is static, and if the returned VarHandle is operated
3555          * on, the field's declaring class will be initialized, if it has not
3556          * already been initialized.
3557          * <p>
3558          * Certain access modes of the returned VarHandle are unsupported under
3559          * the following conditions:
3560          * <ul>
3561          * <li>if the field is declared {@code final}, then the write, atomic
3562          *     update, numeric atomic update, and bitwise atomic update access
3563          *     modes are unsupported.
3564          * <li>if the field type is anything other than {@code byte},
3565          *     {@code short}, {@code char}, {@code int}, {@code long},
3566          *     {@code float}, or {@code double} then numeric atomic update
3567          *     access modes are unsupported.
3568          * <li>if the field type is anything other than {@code boolean},
3569          *     {@code byte}, {@code short}, {@code char}, {@code int} or
3570          *     {@code long} then bitwise atomic update access modes are
3571          *     unsupported.
3572          * </ul>
3573          * <p>
3574          * If the field is declared {@code volatile} then the returned VarHandle
3575          * will override access to the field (effectively ignore the
3576          * {@code volatile} declaration) in accordance to its specified
3577          * access modes.
3578          * <p>
3579          * If the field type is {@code float} or {@code double} then numeric
3580          * and atomic update access modes compare values using their bitwise
3581          * representation (see {@link Float#floatToRawIntBits} and
3582          * {@link Double#doubleToRawLongBits}, respectively).
3583          * @apiNote
3584          * Bitwise comparison of {@code float} values or {@code double} values,
3585          * as performed by the numeric and atomic update access modes, differ
3586          * from the primitive {@code ==} operator and the {@link Float#equals}
3587          * and {@link Double#equals} methods, specifically with respect to
3588          * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
3589          * Care should be taken when performing a compare and set or a compare
3590          * and exchange operation with such values since the operation may
3591          * unexpectedly fail.
3592          * There are many possible NaN values that are considered to be
3593          * {@code NaN} in Java, although no IEEE 754 floating-point operation
3594          * provided by Java can distinguish between them.  Operation failure can
3595          * occur if the expected or witness value is a NaN value and it is
3596          * transformed (perhaps in a platform specific manner) into another NaN
3597          * value, and thus has a different bitwise representation (see
3598          * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
3599          * details).
3600          * The values {@code -0.0} and {@code +0.0} have different bitwise
3601          * representations but are considered equal when using the primitive
3602          * {@code ==} operator.  Operation failure can occur if, for example, a
3603          * numeric algorithm computes an expected value to be say {@code -0.0}
3604          * and previously computed the witness value to be say {@code +0.0}.
3605          * @param f the reflected field, with a field of type {@code T}, and
3606          * a declaring class of type {@code R}
3607          * @return a VarHandle giving access to non-static fields or a static
3608          * field
3609          * @throws IllegalAccessException if access checking fails
3610          * @throws NullPointerException if the argument is null
3611          * @since 9
3612          */
3613         public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException {
3614             MemberName getField = new MemberName(f, false);
3615             MemberName putField = new MemberName(f, true);
3616             return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(),
3617                                                       f.getDeclaringClass(), getField, putField);
3618         }
3619 
3620         /**
3621          * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a>
3622          * created by this lookup object or a similar one.
3623          * Security and access checks are performed to ensure that this lookup object
3624          * is capable of reproducing the target method handle.
3625          * This means that the cracking may fail if target is a direct method handle
3626          * but was created by an unrelated lookup object.
3627          * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>
3628          * and was created by a lookup object for a different class.
3629          * @param target a direct method handle to crack into symbolic reference components
3630          * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object
3631          * @throws    SecurityException if a security manager is present and it
3632          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
3633          * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails
3634          * @throws    NullPointerException if the target is {@code null}
3635          * @see MethodHandleInfo
3636          * @since 1.8
3637          */
3638         public MethodHandleInfo revealDirect(MethodHandle target) {
3639             if (!target.isCrackable()) {
3640                 throw newIllegalArgumentException("not a direct method handle");
3641             }
3642             MemberName member = target.internalMemberName();
3643             Class<?> defc = member.getDeclaringClass();
3644             byte refKind = member.getReferenceKind();
3645             assert(MethodHandleNatives.refKindIsValid(refKind));
3646             if (refKind == REF_invokeSpecial && !target.isInvokeSpecial())
3647                 // Devirtualized method invocation is usually formally virtual.
3648                 // To avoid creating extra MemberName objects for this common case,
3649                 // we encode this extra degree of freedom using MH.isInvokeSpecial.
3650                 refKind = REF_invokeVirtual;
3651             if (refKind == REF_invokeVirtual && defc.isInterface())
3652                 // Symbolic reference is through interface but resolves to Object method (toString, etc.)
3653                 refKind = REF_invokeInterface;
3654             // Check SM permissions and member access before cracking.
3655             try {
3656                 checkAccess(refKind, defc, member);
3657                 checkSecurityManager(defc, member);
3658             } catch (IllegalAccessException ex) {
3659                 throw new IllegalArgumentException(ex);
3660             }
3661             if (allowedModes != TRUSTED && member.isCallerSensitive()) {
3662                 Class<?> callerClass = target.internalCallerClass();
3663                 if ((lookupModes() & ORIGINAL) == 0 || callerClass != lookupClass())
3664                     throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass);
3665             }
3666             // Produce the handle to the results.
3667             return new InfoFromMemberName(this, member, refKind);
3668         }
3669 
3670         /// Helper methods, all package-private.
3671 
3672         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException {
3673             checkSymbolicClass(refc);  // do this before attempting to resolve
3674             Objects.requireNonNull(name);
3675             Objects.requireNonNull(type);
3676             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3677                                             NoSuchFieldException.class);
3678         }
3679 
3680         MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
3681             checkSymbolicClass(refc);  // do this before attempting to resolve
3682             Objects.requireNonNull(type);
3683             checkMethodName(refKind, name);  // implicit null-check of name
3684             return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes,
3685                                             NoSuchMethodException.class);
3686         }
3687 
3688         MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException {
3689             checkSymbolicClass(member.getDeclaringClass());  // do this before attempting to resolve
3690             Objects.requireNonNull(member.getName());
3691             Objects.requireNonNull(member.getType());
3692             return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), allowedModes,
3693                                             ReflectiveOperationException.class);
3694         }
3695 
3696         MemberName resolveOrNull(byte refKind, MemberName member) {
3697             // do this before attempting to resolve
3698             if (!isClassAccessible(member.getDeclaringClass())) {
3699                 return null;
3700             }
3701             Objects.requireNonNull(member.getName());
3702             Objects.requireNonNull(member.getType());
3703             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull(), allowedModes);
3704         }
3705 
3706         MemberName resolveOrNull(byte refKind, Class<?> refc, String name, MethodType type) {
3707             // do this before attempting to resolve
3708             if (!isClassAccessible(refc)) {
3709                 return null;
3710             }
3711             Objects.requireNonNull(type);
3712             // implicit null-check of name
3713             if (name.startsWith("<") && refKind != REF_newInvokeSpecial) {
3714                 return null;
3715             }
3716             return IMPL_NAMES.resolveOrNull(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), allowedModes);
3717         }
3718 
3719         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
3720             if (!isClassAccessible(refc)) {
3721                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
3722             }
3723         }
3724 
3725         boolean isClassAccessible(Class<?> refc) {
3726             Objects.requireNonNull(refc);
3727             Class<?> caller = lookupClassOrNull();
3728             Class<?> type = refc;
3729             while (type.isArray()) {
3730                 type = type.getComponentType();
3731             }
3732             return caller == null || VerifyAccess.isClassAccessible(type, caller, prevLookupClass, allowedModes);
3733         }
3734 
3735         /** Check name for an illegal leading "&lt;" character. */
3736         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
3737             // "<init>" can only be invoked via invokespecial or it's a static init factory
3738             if (name.startsWith("<") && refKind != REF_newInvokeSpecial &&
3739                     !(refKind == REF_invokeStatic && name.equals("<init>"))) {
3740                     throw new NoSuchMethodException("illegal method name: " + name);
3741             }
3742         }
3743 
3744         /**
3745          * Find my trustable caller class if m is a caller sensitive method.
3746          * If this lookup object has original full privilege access, then the caller class is the lookupClass.
3747          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
3748          */
3749         Lookup findBoundCallerLookup(MemberName m) throws IllegalAccessException {
3750             if (MethodHandleNatives.isCallerSensitive(m) && (lookupModes() & ORIGINAL) == 0) {
3751                 // Only lookups with full privilege access are allowed to resolve caller-sensitive methods
3752                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
3753             }
3754             return this;
3755         }
3756 
3757         /**
3758          * Returns {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3759          * @return {@code true} if this lookup has {@code PRIVATE} and {@code MODULE} access.
3760          *
3761          * @deprecated This method was originally designed to test {@code PRIVATE} access
3762          * that implies full privilege access but {@code MODULE} access has since become
3763          * independent of {@code PRIVATE} access.  It is recommended to call
3764          * {@link #hasFullPrivilegeAccess()} instead.
3765          * @since 9
3766          */
3767         @Deprecated(since="14")
3768         public boolean hasPrivateAccess() {
3769             return hasFullPrivilegeAccess();
3770         }
3771 
3772         /**
3773          * Returns {@code true} if this lookup has <em>full privilege access</em>,
3774          * i.e. {@code PRIVATE} and {@code MODULE} access.
3775          * A {@code Lookup} object must have full privilege access in order to
3776          * access all members that are allowed to the
3777          * {@linkplain #lookupClass() lookup class}.
3778          *
3779          * @return {@code true} if this lookup has full privilege access.
3780          * @since 14
3781          * @see <a href="MethodHandles.Lookup.html#privacc">private and module access</a>
3782          */
3783         public boolean hasFullPrivilegeAccess() {
3784             return (allowedModes & (PRIVATE|MODULE)) == (PRIVATE|MODULE);
3785         }
3786 
3787         /**
3788          * Perform steps 1 and 2b <a href="MethodHandles.Lookup.html#secmgr">access checks</a>
3789          * for ensureInitialzed, findClass or accessClass.
3790          */
3791         void checkSecurityManager(Class<?> refc) {
3792             if (allowedModes == TRUSTED)  return;
3793 
3794             @SuppressWarnings("removal")
3795             SecurityManager smgr = System.getSecurityManager();
3796             if (smgr == null)  return;
3797 
3798             // Step 1:
3799             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3800             if (!fullPrivilegeLookup ||
3801                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3802                 ReflectUtil.checkPackageAccess(refc);
3803             }
3804 
3805             // Step 2b:
3806             if (!fullPrivilegeLookup) {
3807                 smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
3808             }
3809         }
3810 
3811         /**
3812          * Perform steps 1, 2a and 3 <a href="MethodHandles.Lookup.html#secmgr">access checks</a>.
3813          * Determines a trustable caller class to compare with refc, the symbolic reference class.
3814          * If this lookup object has full privilege access except original access,
3815          * then the caller class is the lookupClass.
3816          *
3817          * Lookup object created by {@link MethodHandles#privateLookupIn(Class, Lookup)}
3818          * from the same module skips the security permission check.
3819          */
3820         void checkSecurityManager(Class<?> refc, MemberName m) {
3821             Objects.requireNonNull(refc);
3822             Objects.requireNonNull(m);
3823 
3824             if (allowedModes == TRUSTED)  return;
3825 
3826             @SuppressWarnings("removal")
3827             SecurityManager smgr = System.getSecurityManager();
3828             if (smgr == null)  return;
3829 
3830             // Step 1:
3831             boolean fullPrivilegeLookup = hasFullPrivilegeAccess();
3832             if (!fullPrivilegeLookup ||
3833                 !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) {
3834                 ReflectUtil.checkPackageAccess(refc);
3835             }
3836 
3837             // Step 2a:
3838             if (m.isPublic()) return;
3839             if (!fullPrivilegeLookup) {
3840                 smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3841             }
3842 
3843             // Step 3:
3844             Class<?> defc = m.getDeclaringClass();
3845             if (!fullPrivilegeLookup && defc.asPrimaryType() != refc.asPrimaryType()) {
3846                 ReflectUtil.checkPackageAccess(defc);
3847             }
3848         }
3849 
3850         void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3851             boolean wantStatic = (refKind == REF_invokeStatic);
3852             String message;
3853             if (m.isObjectConstructor())
3854                 message = "expected a method, not a constructor";
3855             else if (!m.isMethod())
3856                 message = "expected a method";
3857             else if (wantStatic != m.isStatic())
3858                 message = wantStatic ? "expected a static method" : "expected a non-static method";
3859             else
3860                 { checkAccess(refKind, refc, m); return; }
3861             throw m.makeAccessException(message, this);
3862         }
3863 
3864         void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3865             boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind);
3866             String message;
3867             if (wantStatic != m.isStatic())
3868                 message = wantStatic ? "expected a static field" : "expected a non-static field";
3869             else
3870                 { checkAccess(refKind, refc, m); return; }
3871             throw m.makeAccessException(message, this);
3872         }
3873 
3874         /** Check public/protected/private bits on the symbolic reference class and its member. */
3875         void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException {
3876             assert(m.referenceKindIsConsistentWith(refKind) &&
3877                    MethodHandleNatives.refKindIsValid(refKind) &&
3878                    (MethodHandleNatives.refKindIsField(refKind) == m.isField()));
3879             int allowedModes = this.allowedModes;
3880             if (allowedModes == TRUSTED)  return;
3881             int mods = m.getModifiers();
3882             if (Modifier.isProtected(mods) &&
3883                     refKind == REF_invokeVirtual &&
3884                     m.getDeclaringClass() == Object.class &&
3885                     m.getName().equals("clone") &&
3886                     refc.isArray()) {
3887                 // The JVM does this hack also.
3888                 // (See ClassVerifier::verify_invoke_instructions
3889                 // and LinkResolver::check_method_accessability.)
3890                 // Because the JVM does not allow separate methods on array types,
3891                 // there is no separate method for int[].clone.
3892                 // All arrays simply inherit Object.clone.
3893                 // But for access checking logic, we make Object.clone
3894                 // (normally protected) appear to be public.
3895                 // Later on, when the DirectMethodHandle is created,
3896                 // its leading argument will be restricted to the
3897                 // requested array type.
3898                 // N.B. The return type is not adjusted, because
3899                 // that is *not* the bytecode behavior.
3900                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
3901             }
3902             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
3903                 // cannot "new" a protected ctor in a different package
3904                 mods ^= Modifier.PROTECTED;
3905             }
3906             if (Modifier.isFinal(mods) &&
3907                     MethodHandleNatives.refKindIsSetter(refKind))
3908                 throw m.makeAccessException("unexpected set of a final field", this);
3909             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
3910             if ((requestedModes & allowedModes) != 0) {
3911                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
3912                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
3913                     return;
3914             } else {
3915                 // Protected members can also be checked as if they were package-private.
3916                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
3917                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
3918                     return;
3919             }
3920             throw m.makeAccessException(accessFailedMessage(refc, m), this);
3921         }
3922 
3923         String accessFailedMessage(Class<?> refc, MemberName m) {
3924             Class<?> defc = m.getDeclaringClass();
3925             int mods = m.getModifiers();
3926             // check the class first:
3927             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
3928                                (defc.asPrimaryType() == refc.asPrimaryType() ||
3929                                 Modifier.isPublic(refc.getModifiers())));
3930             if (!classOK && (allowedModes & PACKAGE) != 0) {
3931                 // ignore previous lookup class to check if default package access
3932                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
3933                            (defc.asPrimaryType() == refc.asPrimaryType() ||
3934                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
3935             }
3936             if (!classOK)
3937                 return "class is not public";
3938             if (Modifier.isPublic(mods))
3939                 return "access to public member failed";  // (how?, module not readable?)
3940             if (Modifier.isPrivate(mods))
3941                 return "member is private";
3942             if (Modifier.isProtected(mods))
3943                 return "member is protected";
3944             return "member is private to package";
3945         }
3946 
3947         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
3948             int allowedModes = this.allowedModes;
3949             if (allowedModes == TRUSTED)  return;
3950             if ((lookupModes() & PRIVATE) == 0
3951                 || (specialCaller != lookupClass()
3952                        // ensure non-abstract methods in superinterfaces can be special-invoked
3953                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
3954                 throw new MemberName(specialCaller).
3955                     makeAccessException("no private access for invokespecial", this);
3956         }
3957 
3958         private boolean restrictProtectedReceiver(MemberName method) {
3959             // The accessing class only has the right to use a protected member
3960             // on itself or a subclass.  Enforce that restriction, from JVMS 5.4.4, etc.
3961             if (!method.isProtected() || method.isStatic()
3962                 || allowedModes == TRUSTED
3963                 || method.getDeclaringClass() == lookupClass()
3964                 || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()))
3965                 return false;
3966             return true;
3967         }
3968         private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException {
3969             assert(!method.isStatic());
3970             // receiver type of mh is too wide; narrow to caller
3971             if (!method.getDeclaringClass().isAssignableFrom(caller)) {
3972                 throw method.makeAccessException("caller class must be a subclass below the method", caller);
3973             }
3974             MethodType rawType = mh.type();
3975             if (caller.isAssignableFrom(rawType.parameterType(0))) return mh; // no need to restrict; already narrow
3976             MethodType narrowType = rawType.changeParameterType(0, caller);
3977             assert(!mh.isVarargsCollector());  // viewAsType will lose varargs-ness
3978             assert(mh.viewAsTypeChecks(narrowType, true));
3979             return mh.copyWith(narrowType, mh.form);
3980         }
3981 
3982         /** Check access and get the requested method. */
3983         private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3984             final boolean doRestrict    = true;
3985             final boolean checkSecurity = true;
3986             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3987         }
3988         /** Check access and get the requested method, for invokespecial with no restriction on the application of narrowing rules. */
3989         private MethodHandle getDirectMethodNoRestrictInvokeSpecial(Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3990             final boolean doRestrict    = false;
3991             final boolean checkSecurity = true;
3992             return getDirectMethodCommon(REF_invokeSpecial, refc, method, checkSecurity, doRestrict, callerLookup);
3993         }
3994         /** Check access and get the requested method, eliding security manager checks. */
3995         private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Lookup callerLookup) throws IllegalAccessException {
3996             final boolean doRestrict    = true;
3997             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
3998             return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerLookup);
3999         }
4000         /** Common code for all methods; do not call directly except from immediately above. */
4001         private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method,
4002                                                    boolean checkSecurity,
4003                                                    boolean doRestrict,
4004                                                    Lookup boundCaller) throws IllegalAccessException {
4005             checkMethod(refKind, refc, method);
4006             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4007             if (checkSecurity)
4008                 checkSecurityManager(refc, method);
4009             assert(!method.isMethodHandleInvoke());
4010             if (refKind == REF_invokeSpecial &&
4011                 refc != lookupClass() &&
4012                 !refc.isInterface() &&
4013                 refc != lookupClass().getSuperclass() &&
4014                 refc.isAssignableFrom(lookupClass())) {
4015                 assert(!method.getName().equals("<init>"));  // not this code path
4016 
4017                 // Per JVMS 6.5, desc. of invokespecial instruction:
4018                 // If the method is in a superclass of the LC,
4019                 // and if our original search was above LC.super,
4020                 // repeat the search (symbolic lookup) from LC.super
4021                 // and continue with the direct superclass of that class,
4022                 // and so forth, until a match is found or no further superclasses exist.
4023                 // FIXME: MemberName.resolve should handle this instead.
4024                 Class<?> refcAsSuper = lookupClass();
4025                 MemberName m2;
4026                 do {
4027                     refcAsSuper = refcAsSuper.getSuperclass();
4028                     m2 = new MemberName(refcAsSuper,
4029                                         method.getName(),
4030                                         method.getMethodType(),
4031                                         REF_invokeSpecial);
4032                     m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull(), allowedModes);
4033                 } while (m2 == null &&         // no method is found yet
4034                          refc != refcAsSuper); // search up to refc
4035                 if (m2 == null)  throw new InternalError(method.toString());
4036                 method = m2;
4037                 refc = refcAsSuper;
4038                 // redo basic checks
4039                 checkMethod(refKind, refc, method);
4040             }
4041             DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method, lookupClass());
4042             MethodHandle mh = dmh;
4043             // Optionally narrow the receiver argument to lookupClass using restrictReceiver.
4044             if ((doRestrict && refKind == REF_invokeSpecial) ||
4045                     (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method))) {
4046                 mh = restrictReceiver(method, dmh, lookupClass());
4047             }
4048             mh = maybeBindCaller(method, mh, boundCaller);
4049             mh = mh.setVarargs(method);
4050             return mh;
4051         }
4052         private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Lookup boundCaller)
4053                                              throws IllegalAccessException {
4054             if (boundCaller.allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method))
4055                 return mh;
4056 
4057             // boundCaller must have full privilege access.
4058             // It should have been checked by findBoundCallerLookup. Safe to check this again.
4059             if ((boundCaller.lookupModes() & ORIGINAL) == 0)
4060                 throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object");
4061 
4062             assert boundCaller.hasFullPrivilegeAccess();
4063 
4064             MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, boundCaller.lookupClass);
4065             // Note: caller will apply varargs after this step happens.
4066             return cbmh;
4067         }
4068 
4069         /** Check access and get the requested field. */
4070         private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4071             final boolean checkSecurity = true;
4072             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4073         }
4074         /** Check access and get the requested field, eliding security manager checks. */
4075         private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException {
4076             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4077             return getDirectFieldCommon(refKind, refc, field, checkSecurity);
4078         }
4079         /** Common code for all fields; do not call directly except from immediately above. */
4080         private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field,
4081                                                   boolean checkSecurity) throws IllegalAccessException {
4082             checkField(refKind, refc, field);
4083             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4084             if (checkSecurity)
4085                 checkSecurityManager(refc, field);
4086             DirectMethodHandle dmh = DirectMethodHandle.make(refc, field);
4087             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) &&
4088                                     restrictProtectedReceiver(field));
4089             if (doRestrict)
4090                 return restrictReceiver(field, dmh, lookupClass());
4091             return dmh;
4092         }
4093         private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind,
4094                                             Class<?> refc, MemberName getField, MemberName putField)
4095                 throws IllegalAccessException {
4096             final boolean checkSecurity = true;
4097             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4098         }
4099         private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind,
4100                                                              Class<?> refc, MemberName getField, MemberName putField)
4101                 throws IllegalAccessException {
4102             final boolean checkSecurity = false;
4103             return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity);
4104         }
4105         private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind,
4106                                                   Class<?> refc, MemberName getField, MemberName putField,
4107                                                   boolean checkSecurity) throws IllegalAccessException {
4108             assert getField.isStatic() == putField.isStatic();
4109             assert getField.isGetter() && putField.isSetter();
4110             assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind);
4111             assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind);
4112 
4113             checkField(getRefKind, refc, getField);
4114             if (checkSecurity)
4115                 checkSecurityManager(refc, getField);
4116 
4117             if (!putField.isFinal()) {
4118                 // A VarHandle does not support updates to final fields, any
4119                 // such VarHandle to a final field will be read-only and
4120                 // therefore the following write-based accessibility checks are
4121                 // only required for non-final fields
4122                 checkField(putRefKind, refc, putField);
4123                 if (checkSecurity)
4124                     checkSecurityManager(refc, putField);
4125             }
4126 
4127             boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) &&
4128                                   restrictProtectedReceiver(getField));
4129             if (doRestrict) {
4130                 assert !getField.isStatic();
4131                 // receiver type of VarHandle is too wide; narrow to caller
4132                 if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) {
4133                     throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass());
4134                 }
4135                 refc = lookupClass();
4136             }
4137             return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(),
4138                                               this.allowedModes == TRUSTED && !getField.isTrustedFinalField());
4139         }
4140         /** Check access and get the requested constructor. */
4141         private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4142             final boolean checkSecurity = true;
4143             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4144         }
4145         /** Check access and get the requested constructor, eliding security manager checks. */
4146         private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException {
4147             final boolean checkSecurity = false;  // not needed for reflection or for linking CONSTANT_MH constants
4148             return getDirectConstructorCommon(refc, ctor, checkSecurity);
4149         }
4150         /** Common code for all constructors; do not call directly except from immediately above. */
4151         private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor,
4152                                                   boolean checkSecurity) throws IllegalAccessException {
4153             assert(ctor.isObjectConstructor());
4154             checkAccess(REF_newInvokeSpecial, refc, ctor);
4155             // Optionally check with the security manager; this isn't needed for unreflect* calls.
4156             if (checkSecurity)
4157                 checkSecurityManager(refc, ctor);
4158             assert(!MethodHandleNatives.isCallerSensitive(ctor));  // maybeBindCaller not relevant here
4159             return DirectMethodHandle.make(ctor).setVarargs(ctor);
4160         }
4161 
4162         /** Hook called from the JVM (via MethodHandleNatives) to link MH constants:
4163          */
4164         /*non-public*/
4165         MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type)
4166                 throws ReflectiveOperationException {
4167             if (!(type instanceof Class || type instanceof MethodType))
4168                 throw new InternalError("unresolved MemberName");
4169             MemberName member = new MemberName(refKind, defc, name, type);
4170             MethodHandle mh = LOOKASIDE_TABLE.get(member);
4171             if (mh != null) {
4172                 checkSymbolicClass(defc);
4173                 return mh;
4174             }
4175             if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
4176                 // Treat MethodHandle.invoke and invokeExact specially.
4177                 mh = findVirtualForMH(member.getName(), member.getMethodType());
4178                 if (mh != null) {
4179                     return mh;
4180                 }
4181             } else if (defc == VarHandle.class && refKind == REF_invokeVirtual) {
4182                 // Treat signature-polymorphic methods on VarHandle specially.
4183                 mh = findVirtualForVH(member.getName(), member.getMethodType());
4184                 if (mh != null) {
4185                     return mh;
4186                 }
4187             }
4188             MemberName resolved = resolveOrFail(refKind, member);
4189             mh = getDirectMethodForConstant(refKind, defc, resolved);
4190             if (mh instanceof DirectMethodHandle
4191                     && canBeCached(refKind, defc, resolved)) {
4192                 MemberName key = mh.internalMemberName();
4193                 if (key != null) {
4194                     key = key.asNormalOriginal();
4195                 }
4196                 if (member.equals(key)) {  // better safe than sorry
4197                     LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh);
4198                 }
4199             }
4200             return mh;
4201         }
4202         private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) {
4203             if (refKind == REF_invokeSpecial) {
4204                 return false;
4205             }
4206             if (!Modifier.isPublic(defc.getModifiers()) ||
4207                     !Modifier.isPublic(member.getDeclaringClass().getModifiers()) ||
4208                     !member.isPublic() ||
4209                     member.isCallerSensitive()) {
4210                 return false;
4211             }
4212             ClassLoader loader = defc.getClassLoader();
4213             if (loader != null) {
4214                 ClassLoader sysl = ClassLoader.getSystemClassLoader();
4215                 boolean found = false;
4216                 while (sysl != null) {
4217                     if (loader == sysl) { found = true; break; }
4218                     sysl = sysl.getParent();
4219                 }
4220                 if (!found) {
4221                     return false;
4222                 }
4223             }
4224             try {
4225                 MemberName resolved2 = publicLookup().resolveOrNull(refKind,
4226                     new MemberName(refKind, defc, member.getName(), member.getType()));
4227                 if (resolved2 == null) {
4228                     return false;
4229                 }
4230                 checkSecurityManager(defc, resolved2);
4231             } catch (SecurityException ex) {
4232                 return false;
4233             }
4234             return true;
4235         }
4236         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
4237                 throws ReflectiveOperationException {
4238             if (MethodHandleNatives.refKindIsField(refKind)) {
4239                 return getDirectFieldNoSecurityManager(refKind, defc, member);
4240             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
4241                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
4242             } else if (refKind == REF_newInvokeSpecial) {
4243                 return getDirectConstructorNoSecurityManager(defc, member);
4244             }
4245             // oops
4246             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
4247         }
4248 
4249         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
4250     }
4251 
4252     /**
4253      * Produces a method handle constructing arrays of a desired type,
4254      * as if by the {@code anewarray} bytecode.
4255      * The return type of the method handle will be the array type.
4256      * The type of its sole argument will be {@code int}, which specifies the size of the array.
4257      *
4258      * <p> If the returned method handle is invoked with a negative
4259      * array size, a {@code NegativeArraySizeException} will be thrown.
4260      *
4261      * @param arrayClass an array type
4262      * @return a method handle which can create arrays of the given type
4263      * @throws NullPointerException if the argument is {@code null}
4264      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
4265      * @see java.lang.reflect.Array#newInstance(Class, int)
4266      * @jvms 6.5 {@code anewarray} Instruction
4267      * @since 9
4268      */
4269     public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException {
4270         if (!arrayClass.isArray()) {
4271             throw newIllegalArgumentException("not an array class: " + arrayClass.getName());
4272         }
4273         MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance).
4274                 bindTo(arrayClass.getComponentType());
4275         return ani.asType(ani.type().changeReturnType(arrayClass));
4276     }
4277 
4278     /**
4279      * Produces a method handle returning the length of an array,
4280      * as if by the {@code arraylength} bytecode.
4281      * The type of the method handle will have {@code int} as return type,
4282      * and its sole argument will be the array type.
4283      *
4284      * <p> If the returned method handle is invoked with a {@code null}
4285      * array reference, a {@code NullPointerException} will be thrown.
4286      *
4287      * @param arrayClass an array type
4288      * @return a method handle which can retrieve the length of an array of the given array type
4289      * @throws NullPointerException if the argument is {@code null}
4290      * @throws IllegalArgumentException if arrayClass is not an array type
4291      * @jvms 6.5 {@code arraylength} Instruction
4292      * @since 9
4293      */
4294     public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException {
4295         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH);
4296     }
4297 
4298     /**
4299      * Produces a method handle giving read access to elements of an array,
4300      * as if by the {@code aaload} bytecode.
4301      * The type of the method handle will have a return type of the array's
4302      * element type.  Its first argument will be the array type,
4303      * and the second will be {@code int}.
4304      *
4305      * <p> When the returned method handle is invoked,
4306      * the array reference and array index are checked.
4307      * A {@code NullPointerException} will be thrown if the array reference
4308      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4309      * thrown if the index is negative or if it is greater than or equal to
4310      * the length of the array.
4311      *
4312      * @param arrayClass an array type
4313      * @return a method handle which can load values from the given array type
4314      * @throws NullPointerException if the argument is null
4315      * @throws  IllegalArgumentException if arrayClass is not an array type
4316      * @jvms 6.5 {@code aaload} Instruction
4317      */
4318     public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
4319         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET);
4320     }
4321 
4322     /**
4323      * Produces a method handle giving write access to elements of an array,
4324      * as if by the {@code astore} bytecode.
4325      * The type of the method handle will have a void return type.
4326      * Its last argument will be the array's element type.
4327      * The first and second arguments will be the array type and int.
4328      *
4329      * <p> When the returned method handle is invoked,
4330      * the array reference and array index are checked.
4331      * A {@code NullPointerException} will be thrown if the array reference
4332      * is {@code null} or if the array's element type is a {@link Class#isPrimitiveValueType()
4333      * a primitive value type} and attempts to set {@code null} in the
4334      * array element.  An {@code ArrayIndexOutOfBoundsException} will be
4335      * thrown if the index is negative or if it is greater than or equal to
4336      * the length of the array.
4337      *
4338      * @param arrayClass the class of an array
4339      * @return a method handle which can store values into the array type
4340      * @throws NullPointerException if the argument is null
4341      * @throws IllegalArgumentException if arrayClass is not an array type
4342      * @jvms 6.5 {@code aastore} Instruction
4343      */
4344     public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
4345         return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET);
4346     }
4347 
4348     /**
4349      * Produces a VarHandle giving access to elements of an array of type
4350      * {@code arrayClass}.  The VarHandle's variable type is the component type
4351      * of {@code arrayClass} and the list of coordinate types is
4352      * {@code (arrayClass, int)}, where the {@code int} coordinate type
4353      * corresponds to an argument that is an index into an array.
4354      * <p>
4355      * Certain access modes of the returned VarHandle are unsupported under
4356      * the following conditions:
4357      * <ul>
4358      * <li>if the component type is anything other than {@code byte},
4359      *     {@code short}, {@code char}, {@code int}, {@code long},
4360      *     {@code float}, or {@code double} then numeric atomic update access
4361      *     modes are unsupported.
4362      * <li>if the component type is anything other than {@code boolean},
4363      *     {@code byte}, {@code short}, {@code char}, {@code int} or
4364      *     {@code long} then bitwise atomic update access modes are
4365      *     unsupported.
4366      * </ul>
4367      * <p>
4368      * If the component type is {@code float} or {@code double} then numeric
4369      * and atomic update access modes compare values using their bitwise
4370      * representation (see {@link Float#floatToRawIntBits} and
4371      * {@link Double#doubleToRawLongBits}, respectively).
4372      *
4373      * <p> When the returned {@code VarHandle} is invoked,
4374      * the array reference and array index are checked.
4375      * A {@code NullPointerException} will be thrown if the array reference
4376      * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
4377      * thrown if the index is negative or if it is greater than or equal to
4378      * the length of the array.
4379      *
4380      * @apiNote
4381      * Bitwise comparison of {@code float} values or {@code double} values,
4382      * as performed by the numeric and atomic update access modes, differ
4383      * from the primitive {@code ==} operator and the {@link Float#equals}
4384      * and {@link Double#equals} methods, specifically with respect to
4385      * comparing NaN values or comparing {@code -0.0} with {@code +0.0}.
4386      * Care should be taken when performing a compare and set or a compare
4387      * and exchange operation with such values since the operation may
4388      * unexpectedly fail.
4389      * There are many possible NaN values that are considered to be
4390      * {@code NaN} in Java, although no IEEE 754 floating-point operation
4391      * provided by Java can distinguish between them.  Operation failure can
4392      * occur if the expected or witness value is a NaN value and it is
4393      * transformed (perhaps in a platform specific manner) into another NaN
4394      * value, and thus has a different bitwise representation (see
4395      * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more
4396      * details).
4397      * The values {@code -0.0} and {@code +0.0} have different bitwise
4398      * representations but are considered equal when using the primitive
4399      * {@code ==} operator.  Operation failure can occur if, for example, a
4400      * numeric algorithm computes an expected value to be say {@code -0.0}
4401      * and previously computed the witness value to be say {@code +0.0}.
4402      * @param arrayClass the class of an array, of type {@code T[]}
4403      * @return a VarHandle giving access to elements of an array
4404      * @throws NullPointerException if the arrayClass is null
4405      * @throws IllegalArgumentException if arrayClass is not an array type
4406      * @since 9
4407      */
4408     public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException {
4409         return VarHandles.makeArrayElementHandle(arrayClass);
4410     }
4411 
4412     /**
4413      * Produces a VarHandle giving access to elements of a {@code byte[]} array
4414      * viewed as if it were a different primitive array type, such as
4415      * {@code int[]} or {@code long[]}.
4416      * The VarHandle's variable type is the component type of
4417      * {@code viewArrayClass} and the list of coordinate types is
4418      * {@code (byte[], int)}, where the {@code int} coordinate type
4419      * corresponds to an argument that is an index into a {@code byte[]} array.
4420      * The returned VarHandle accesses bytes at an index in a {@code byte[]}
4421      * array, composing bytes to or from a value of the component type of
4422      * {@code viewArrayClass} according to the given endianness.
4423      * <p>
4424      * The supported component types (variables types) are {@code short},
4425      * {@code char}, {@code int}, {@code long}, {@code float} and
4426      * {@code double}.
4427      * <p>
4428      * Access of bytes at a given index will result in an
4429      * {@code ArrayIndexOutOfBoundsException} if the index is less than {@code 0}
4430      * or greater than the {@code byte[]} array length minus the size (in bytes)
4431      * of {@code T}.
4432      * <p>
4433      * Access of bytes at an index may be aligned or misaligned for {@code T},
4434      * with respect to the underlying memory address, {@code A} say, associated
4435      * with the array and index.
4436      * If access is misaligned then access for anything other than the
4437      * {@code get} and {@code set} access modes will result in an
4438      * {@code IllegalStateException}.  In such cases atomic access is only
4439      * guaranteed with respect to the largest power of two that divides the GCD
4440      * of {@code A} and the size (in bytes) of {@code T}.
4441      * If access is aligned then following access modes are supported and are
4442      * guaranteed to support atomic access:
4443      * <ul>
4444      * <li>read write access modes for all {@code T}, with the exception of
4445      *     access modes {@code get} and {@code set} for {@code long} and
4446      *     {@code double} on 32-bit platforms.
4447      * <li>atomic update access modes for {@code int}, {@code long},
4448      *     {@code float} or {@code double}.
4449      *     (Future major platform releases of the JDK may support additional
4450      *     types for certain currently unsupported access modes.)
4451      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4452      *     (Future major platform releases of the JDK may support additional
4453      *     numeric types for certain currently unsupported access modes.)
4454      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4455      *     (Future major platform releases of the JDK may support additional
4456      *     numeric types for certain currently unsupported access modes.)
4457      * </ul>
4458      * <p>
4459      * Misaligned access, and therefore atomicity guarantees, may be determined
4460      * for {@code byte[]} arrays without operating on a specific array.  Given
4461      * an {@code index}, {@code T} and its corresponding boxed type,
4462      * {@code T_BOX}, misalignment may be determined as follows:
4463      * <pre>{@code
4464      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4465      * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]).
4466      *     alignmentOffset(0, sizeOfT);
4467      * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT;
4468      * boolean isMisaligned = misalignedAtIndex != 0;
4469      * }</pre>
4470      * <p>
4471      * If the variable type is {@code float} or {@code double} then atomic
4472      * update access modes compare values using their bitwise representation
4473      * (see {@link Float#floatToRawIntBits} and
4474      * {@link Double#doubleToRawLongBits}, respectively).
4475      * @param viewArrayClass the view array class, with a component type of
4476      * type {@code T}
4477      * @param byteOrder the endianness of the view array elements, as
4478      * stored in the underlying {@code byte} array
4479      * @return a VarHandle giving access to elements of a {@code byte[]} array
4480      * viewed as if elements corresponding to the components type of the view
4481      * array class
4482      * @throws NullPointerException if viewArrayClass or byteOrder is null
4483      * @throws IllegalArgumentException if viewArrayClass is not an array type
4484      * @throws UnsupportedOperationException if the component type of
4485      * viewArrayClass is not supported as a variable type
4486      * @since 9
4487      */
4488     public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass,
4489                                      ByteOrder byteOrder) throws IllegalArgumentException {
4490         Objects.requireNonNull(byteOrder);
4491         return VarHandles.byteArrayViewHandle(viewArrayClass,
4492                                               byteOrder == ByteOrder.BIG_ENDIAN);
4493     }
4494 
4495     /**
4496      * Produces a VarHandle giving access to elements of a {@code ByteBuffer}
4497      * viewed as if it were an array of elements of a different primitive
4498      * component type to that of {@code byte}, such as {@code int[]} or
4499      * {@code long[]}.
4500      * The VarHandle's variable type is the component type of
4501      * {@code viewArrayClass} and the list of coordinate types is
4502      * {@code (ByteBuffer, int)}, where the {@code int} coordinate type
4503      * corresponds to an argument that is an index into a {@code byte[]} array.
4504      * The returned VarHandle accesses bytes at an index in a
4505      * {@code ByteBuffer}, composing bytes to or from a value of the component
4506      * type of {@code viewArrayClass} according to the given endianness.
4507      * <p>
4508      * The supported component types (variables types) are {@code short},
4509      * {@code char}, {@code int}, {@code long}, {@code float} and
4510      * {@code double}.
4511      * <p>
4512      * Access will result in a {@code ReadOnlyBufferException} for anything
4513      * other than the read access modes if the {@code ByteBuffer} is read-only.
4514      * <p>
4515      * Access of bytes at a given index will result in an
4516      * {@code IndexOutOfBoundsException} if the index is less than {@code 0}
4517      * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of
4518      * {@code T}.
4519      * <p>
4520      * Access of bytes at an index may be aligned or misaligned for {@code T},
4521      * with respect to the underlying memory address, {@code A} say, associated
4522      * with the {@code ByteBuffer} and index.
4523      * If access is misaligned then access for anything other than the
4524      * {@code get} and {@code set} access modes will result in an
4525      * {@code IllegalStateException}.  In such cases atomic access is only
4526      * guaranteed with respect to the largest power of two that divides the GCD
4527      * of {@code A} and the size (in bytes) of {@code T}.
4528      * If access is aligned then following access modes are supported and are
4529      * guaranteed to support atomic access:
4530      * <ul>
4531      * <li>read write access modes for all {@code T}, with the exception of
4532      *     access modes {@code get} and {@code set} for {@code long} and
4533      *     {@code double} on 32-bit platforms.
4534      * <li>atomic update access modes for {@code int}, {@code long},
4535      *     {@code float} or {@code double}.
4536      *     (Future major platform releases of the JDK may support additional
4537      *     types for certain currently unsupported access modes.)
4538      * <li>numeric atomic update access modes for {@code int} and {@code long}.
4539      *     (Future major platform releases of the JDK may support additional
4540      *     numeric types for certain currently unsupported access modes.)
4541      * <li>bitwise atomic update access modes for {@code int} and {@code long}.
4542      *     (Future major platform releases of the JDK may support additional
4543      *     numeric types for certain currently unsupported access modes.)
4544      * </ul>
4545      * <p>
4546      * Misaligned access, and therefore atomicity guarantees, may be determined
4547      * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an
4548      * {@code index}, {@code T} and its corresponding boxed type,
4549      * {@code T_BOX}, as follows:
4550      * <pre>{@code
4551      * int sizeOfT = T_BOX.BYTES;  // size in bytes of T
4552      * ByteBuffer bb = ...
4553      * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT);
4554      * boolean isMisaligned = misalignedAtIndex != 0;
4555      * }</pre>
4556      * <p>
4557      * If the variable type is {@code float} or {@code double} then atomic
4558      * update access modes compare values using their bitwise representation
4559      * (see {@link Float#floatToRawIntBits} and
4560      * {@link Double#doubleToRawLongBits}, respectively).
4561      * @param viewArrayClass the view array class, with a component type of
4562      * type {@code T}
4563      * @param byteOrder the endianness of the view array elements, as
4564      * stored in the underlying {@code ByteBuffer} (Note this overrides the
4565      * endianness of a {@code ByteBuffer})
4566      * @return a VarHandle giving access to elements of a {@code ByteBuffer}
4567      * viewed as if elements corresponding to the components type of the view
4568      * array class
4569      * @throws NullPointerException if viewArrayClass or byteOrder is null
4570      * @throws IllegalArgumentException if viewArrayClass is not an array type
4571      * @throws UnsupportedOperationException if the component type of
4572      * viewArrayClass is not supported as a variable type
4573      * @since 9
4574      */
4575     public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass,
4576                                       ByteOrder byteOrder) throws IllegalArgumentException {
4577         Objects.requireNonNull(byteOrder);
4578         return VarHandles.makeByteBufferViewHandle(viewArrayClass,
4579                                                    byteOrder == ByteOrder.BIG_ENDIAN);
4580     }
4581 
4582 
4583     /// method handle invocation (reflective style)
4584 
4585     /**
4586      * Produces a method handle which will invoke any method handle of the
4587      * given {@code type}, with a given number of trailing arguments replaced by
4588      * a single trailing {@code Object[]} array.
4589      * The resulting invoker will be a method handle with the following
4590      * arguments:
4591      * <ul>
4592      * <li>a single {@code MethodHandle} target
4593      * <li>zero or more leading values (counted by {@code leadingArgCount})
4594      * <li>an {@code Object[]} array containing trailing arguments
4595      * </ul>
4596      * <p>
4597      * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with
4598      * the indicated {@code type}.
4599      * That is, if the target is exactly of the given {@code type}, it will behave
4600      * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType}
4601      * is used to convert the target to the required {@code type}.
4602      * <p>
4603      * The type of the returned invoker will not be the given {@code type}, but rather
4604      * will have all parameters except the first {@code leadingArgCount}
4605      * replaced by a single array of type {@code Object[]}, which will be
4606      * the final parameter.
4607      * <p>
4608      * Before invoking its target, the invoker will spread the final array, apply
4609      * reference casts as necessary, and unbox and widen primitive arguments.
4610      * If, when the invoker is called, the supplied array argument does
4611      * not have the correct number of elements, the invoker will throw
4612      * an {@link IllegalArgumentException} instead of invoking the target.
4613      * <p>
4614      * This method is equivalent to the following code (though it may be more efficient):
4615      * <blockquote><pre>{@code
4616 MethodHandle invoker = MethodHandles.invoker(type);
4617 int spreadArgCount = type.parameterCount() - leadingArgCount;
4618 invoker = invoker.asSpreader(Object[].class, spreadArgCount);
4619 return invoker;
4620      * }</pre></blockquote>
4621      * This method throws no reflective or security exceptions.
4622      * @param type the desired target type
4623      * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target
4624      * @return a method handle suitable for invoking any method handle of the given type
4625      * @throws NullPointerException if {@code type} is null
4626      * @throws IllegalArgumentException if {@code leadingArgCount} is not in
4627      *                  the range from 0 to {@code type.parameterCount()} inclusive,
4628      *                  or if the resulting method handle's type would have
4629      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4630      */
4631     public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) {
4632         if (leadingArgCount < 0 || leadingArgCount > type.parameterCount())
4633             throw newIllegalArgumentException("bad argument count", leadingArgCount);
4634         type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount);
4635         return type.invokers().spreadInvoker(leadingArgCount);
4636     }
4637 
4638     /**
4639      * Produces a special <em>invoker method handle</em> which can be used to
4640      * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}.
4641      * The resulting invoker will have a type which is
4642      * exactly equal to the desired type, except that it will accept
4643      * an additional leading argument of type {@code MethodHandle}.
4644      * <p>
4645      * This method is equivalent to the following code (though it may be more efficient):
4646      * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)}
4647      *
4648      * <p style="font-size:smaller;">
4649      * <em>Discussion:</em>
4650      * Invoker method handles can be useful when working with variable method handles
4651      * of unknown types.
4652      * For example, to emulate an {@code invokeExact} call to a variable method
4653      * handle {@code M}, extract its type {@code T},
4654      * look up the invoker method {@code X} for {@code T},
4655      * and call the invoker method, as {@code X.invoke(T, A...)}.
4656      * (It would not work to call {@code X.invokeExact}, since the type {@code T}
4657      * is unknown.)
4658      * If spreading, collecting, or other argument transformations are required,
4659      * they can be applied once to the invoker {@code X} and reused on many {@code M}
4660      * method handle values, as long as they are compatible with the type of {@code X}.
4661      * <p style="font-size:smaller;">
4662      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4663      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4664      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4665      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4666      * <p>
4667      * This method throws no reflective or security exceptions.
4668      * @param type the desired target type
4669      * @return a method handle suitable for invoking any method handle of the given type
4670      * @throws IllegalArgumentException if the resulting method handle's type would have
4671      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4672      */
4673     public static MethodHandle exactInvoker(MethodType type) {
4674         return type.invokers().exactInvoker();
4675     }
4676 
4677     /**
4678      * Produces a special <em>invoker method handle</em> which can be used to
4679      * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}.
4680      * The resulting invoker will have a type which is
4681      * exactly equal to the desired type, except that it will accept
4682      * an additional leading argument of type {@code MethodHandle}.
4683      * <p>
4684      * Before invoking its target, if the target differs from the expected type,
4685      * the invoker will apply reference casts as
4686      * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}.
4687      * Similarly, the return value will be converted as necessary.
4688      * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle},
4689      * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}.
4690      * <p>
4691      * This method is equivalent to the following code (though it may be more efficient):
4692      * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)}
4693      * <p style="font-size:smaller;">
4694      * <em>Discussion:</em>
4695      * A {@linkplain MethodType#genericMethodType general method type} is one which
4696      * mentions only {@code Object} arguments and return values.
4697      * An invoker for such a type is capable of calling any method handle
4698      * of the same arity as the general type.
4699      * <p style="font-size:smaller;">
4700      * <em>(Note:  The invoker method is not available via the Core Reflection API.
4701      * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}
4702      * on the declared {@code invokeExact} or {@code invoke} method will raise an
4703      * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em>
4704      * <p>
4705      * This method throws no reflective or security exceptions.
4706      * @param type the desired target type
4707      * @return a method handle suitable for invoking any method handle convertible to the given type
4708      * @throws IllegalArgumentException if the resulting method handle's type would have
4709      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
4710      */
4711     public static MethodHandle invoker(MethodType type) {
4712         return type.invokers().genericInvoker();
4713     }
4714 
4715     /**
4716      * Produces a special <em>invoker method handle</em> which can be used to
4717      * invoke a signature-polymorphic access mode method on any VarHandle whose
4718      * associated access mode type is compatible with the given type.
4719      * The resulting invoker will have a type which is exactly equal to the
4720      * desired given type, except that it will accept an additional leading
4721      * argument of type {@code VarHandle}.
4722      *
4723      * @param accessMode the VarHandle access mode
4724      * @param type the desired target type
4725      * @return a method handle suitable for invoking an access mode method of
4726      *         any VarHandle whose access mode type is of the given type.
4727      * @since 9
4728      */
4729     public static MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4730         return type.invokers().varHandleMethodExactInvoker(accessMode);
4731     }
4732 
4733     /**
4734      * Produces a special <em>invoker method handle</em> which can be used to
4735      * invoke a signature-polymorphic access mode method on any VarHandle whose
4736      * associated access mode type is compatible with the given type.
4737      * The resulting invoker will have a type which is exactly equal to the
4738      * desired given type, except that it will accept an additional leading
4739      * argument of type {@code VarHandle}.
4740      * <p>
4741      * Before invoking its target, if the access mode type differs from the
4742      * desired given type, the invoker will apply reference casts as necessary
4743      * and box, unbox, or widen primitive values, as if by
4744      * {@link MethodHandle#asType asType}.  Similarly, the return value will be
4745      * converted as necessary.
4746      * <p>
4747      * This method is equivalent to the following code (though it may be more
4748      * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)}
4749      *
4750      * @param accessMode the VarHandle access mode
4751      * @param type the desired target type
4752      * @return a method handle suitable for invoking an access mode method of
4753      *         any VarHandle whose access mode type is convertible to the given
4754      *         type.
4755      * @since 9
4756      */
4757     public static MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) {
4758         return type.invokers().varHandleMethodInvoker(accessMode);
4759     }
4760 
4761     /*non-public*/
4762     static MethodHandle basicInvoker(MethodType type) {
4763         return type.invokers().basicInvoker();
4764     }
4765 
4766      /// method handle modification (creation from other method handles)
4767 
4768     /**
4769      * Produces a method handle which adapts the type of the
4770      * given method handle to a new type by pairwise argument and return type conversion.
4771      * The original type and new type must have the same number of arguments.
4772      * The resulting method handle is guaranteed to report a type
4773      * which is equal to the desired new type.
4774      * <p>
4775      * If the original type and new type are equal, returns target.
4776      * <p>
4777      * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType},
4778      * and some additional conversions are also applied if those conversions fail.
4779      * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied
4780      * if possible, before or instead of any conversions done by {@code asType}:
4781      * <ul>
4782      * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type,
4783      *     then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast.
4784      *     (This treatment of interfaces follows the usage of the bytecode verifier.)
4785      * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive,
4786      *     the boolean is converted to a byte value, 1 for true, 0 for false.
4787      *     (This treatment follows the usage of the bytecode verifier.)
4788      * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive,
4789      *     <em>T0</em> is converted to byte via Java casting conversion (JLS {@jls 5.5}),
4790      *     and the low order bit of the result is tested, as if by {@code (x & 1) != 0}.
4791      * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean,
4792      *     then a Java casting conversion (JLS {@jls 5.5}) is applied.
4793      *     (Specifically, <em>T0</em> will convert to <em>T1</em> by
4794      *     widening and/or narrowing.)
4795      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
4796      *     conversion will be applied at runtime, possibly followed
4797      *     by a Java casting conversion (JLS {@jls 5.5}) on the primitive value,
4798      *     possibly followed by a conversion from byte to boolean by testing
4799      *     the low-order bit.
4800      * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive,
4801      *     and if the reference is null at runtime, a zero value is introduced.
4802      * </ul>
4803      * @param target the method handle to invoke after arguments are retyped
4804      * @param newType the expected type of the new method handle
4805      * @return a method handle which delegates to the target after performing
4806      *           any necessary argument conversions, and arranges for any
4807      *           necessary return value conversions
4808      * @throws NullPointerException if either argument is null
4809      * @throws WrongMethodTypeException if the conversion cannot be made
4810      * @see MethodHandle#asType
4811      */
4812     public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) {
4813         explicitCastArgumentsChecks(target, newType);
4814         // use the asTypeCache when possible:
4815         MethodType oldType = target.type();
4816         if (oldType == newType)  return target;
4817         if (oldType.explicitCastEquivalentToAsType(newType)) {
4818             return target.asFixedArity().asType(newType);
4819         }
4820         return MethodHandleImpl.makePairwiseConvert(target, newType, false);
4821     }
4822 
4823     private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) {
4824         if (target.type().parameterCount() != newType.parameterCount()) {
4825             throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType);
4826         }
4827     }
4828 
4829     /**
4830      * Produces a method handle which adapts the calling sequence of the
4831      * given method handle to a new type, by reordering the arguments.
4832      * The resulting method handle is guaranteed to report a type
4833      * which is equal to the desired new type.
4834      * <p>
4835      * The given array controls the reordering.
4836      * Call {@code #I} the number of incoming parameters (the value
4837      * {@code newType.parameterCount()}, and call {@code #O} the number
4838      * of outgoing parameters (the value {@code target.type().parameterCount()}).
4839      * Then the length of the reordering array must be {@code #O},
4840      * and each element must be a non-negative number less than {@code #I}.
4841      * For every {@code N} less than {@code #O}, the {@code N}-th
4842      * outgoing argument will be taken from the {@code I}-th incoming
4843      * argument, where {@code I} is {@code reorder[N]}.
4844      * <p>
4845      * No argument or return value conversions are applied.
4846      * The type of each incoming argument, as determined by {@code newType},
4847      * must be identical to the type of the corresponding outgoing parameter
4848      * or parameters in the target method handle.
4849      * The return type of {@code newType} must be identical to the return
4850      * type of the original target.
4851      * <p>
4852      * The reordering array need not specify an actual permutation.
4853      * An incoming argument will be duplicated if its index appears
4854      * more than once in the array, and an incoming argument will be dropped
4855      * if its index does not appear in the array.
4856      * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments},
4857      * incoming arguments which are not mentioned in the reordering array
4858      * may be of any type, as determined only by {@code newType}.
4859      * <blockquote><pre>{@code
4860 import static java.lang.invoke.MethodHandles.*;
4861 import static java.lang.invoke.MethodType.*;
4862 ...
4863 MethodType intfn1 = methodType(int.class, int.class);
4864 MethodType intfn2 = methodType(int.class, int.class, int.class);
4865 MethodHandle sub = ... (int x, int y) -> (x-y) ...;
4866 assert(sub.type().equals(intfn2));
4867 MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1);
4868 MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0);
4869 assert((int)rsub.invokeExact(1, 100) == 99);
4870 MethodHandle add = ... (int x, int y) -> (x+y) ...;
4871 assert(add.type().equals(intfn2));
4872 MethodHandle twice = permuteArguments(add, intfn1, 0, 0);
4873 assert(twice.type().equals(intfn1));
4874 assert((int)twice.invokeExact(21) == 42);
4875      * }</pre></blockquote>
4876      * <p>
4877      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
4878      * variable-arity method handle}, even if the original target method handle was.
4879      * @param target the method handle to invoke after arguments are reordered
4880      * @param newType the expected type of the new method handle
4881      * @param reorder an index array which controls the reordering
4882      * @return a method handle which delegates to the target after it
4883      *           drops unused arguments and moves and/or duplicates the other arguments
4884      * @throws NullPointerException if any argument is null
4885      * @throws IllegalArgumentException if the index array length is not equal to
4886      *                  the arity of the target, or if any index array element
4887      *                  not a valid index for a parameter of {@code newType},
4888      *                  or if two corresponding parameter types in
4889      *                  {@code target.type()} and {@code newType} are not identical,
4890      */
4891     public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) {
4892         reorder = reorder.clone();  // get a private copy
4893         MethodType oldType = target.type();
4894         permuteArgumentChecks(reorder, newType, oldType);
4895         // first detect dropped arguments and handle them separately
4896         int[] originalReorder = reorder;
4897         BoundMethodHandle result = target.rebind();
4898         LambdaForm form = result.form;
4899         int newArity = newType.parameterCount();
4900         // Normalize the reordering into a real permutation,
4901         // by removing duplicates and adding dropped elements.
4902         // This somewhat improves lambda form caching, as well
4903         // as simplifying the transform by breaking it up into steps.
4904         for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) {
4905             if (ddIdx > 0) {
4906                 // We found a duplicated entry at reorder[ddIdx].
4907                 // Example:  (x,y,z)->asList(x,y,z)
4908                 // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1)
4909                 // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0)
4910                 // The starred element corresponds to the argument
4911                 // deleted by the dupArgumentForm transform.
4912                 int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos];
4913                 boolean killFirst = false;
4914                 for (int val; (val = reorder[--dstPos]) != dupVal; ) {
4915                     // Set killFirst if the dup is larger than an intervening position.
4916                     // This will remove at least one inversion from the permutation.
4917                     if (dupVal > val) killFirst = true;
4918                 }
4919                 if (!killFirst) {
4920                     srcPos = dstPos;
4921                     dstPos = ddIdx;
4922                 }
4923                 form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos);
4924                 assert (reorder[srcPos] == reorder[dstPos]);
4925                 oldType = oldType.dropParameterTypes(dstPos, dstPos + 1);
4926                 // contract the reordering by removing the element at dstPos
4927                 int tailPos = dstPos + 1;
4928                 System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos);
4929                 reorder = Arrays.copyOf(reorder, reorder.length - 1);
4930             } else {
4931                 int dropVal = ~ddIdx, insPos = 0;
4932                 while (insPos < reorder.length && reorder[insPos] < dropVal) {
4933                     // Find first element of reorder larger than dropVal.
4934                     // This is where we will insert the dropVal.
4935                     insPos += 1;
4936                 }
4937                 Class<?> ptype = newType.parameterType(dropVal);
4938                 form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype));
4939                 oldType = oldType.insertParameterTypes(insPos, ptype);
4940                 // expand the reordering by inserting an element at insPos
4941                 int tailPos = insPos + 1;
4942                 reorder = Arrays.copyOf(reorder, reorder.length + 1);
4943                 System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos);
4944                 reorder[insPos] = dropVal;
4945             }
4946             assert (permuteArgumentChecks(reorder, newType, oldType));
4947         }
4948         assert (reorder.length == newArity);  // a perfect permutation
4949         // Note:  This may cache too many distinct LFs. Consider backing off to varargs code.
4950         form = form.editor().permuteArgumentsForm(1, reorder);
4951         if (newType == result.type() && form == result.internalForm())
4952             return result;
4953         return result.copyWith(newType, form);
4954     }
4955 
4956     /**
4957      * Return an indication of any duplicate or omission in reorder.
4958      * If the reorder contains a duplicate entry, return the index of the second occurrence.
4959      * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder.
4960      * Otherwise, return zero.
4961      * If an element not in [0..newArity-1] is encountered, return reorder.length.
4962      */
4963     private static int findFirstDupOrDrop(int[] reorder, int newArity) {
4964         final int BIT_LIMIT = 63;  // max number of bits in bit mask
4965         if (newArity < BIT_LIMIT) {
4966             long mask = 0;
4967             for (int i = 0; i < reorder.length; i++) {
4968                 int arg = reorder[i];
4969                 if (arg >= newArity) {
4970                     return reorder.length;
4971                 }
4972                 long bit = 1L << arg;
4973                 if ((mask & bit) != 0) {
4974                     return i;  // >0 indicates a dup
4975                 }
4976                 mask |= bit;
4977             }
4978             if (mask == (1L << newArity) - 1) {
4979                 assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity);
4980                 return 0;
4981             }
4982             // find first zero
4983             long zeroBit = Long.lowestOneBit(~mask);
4984             int zeroPos = Long.numberOfTrailingZeros(zeroBit);
4985             assert(zeroPos <= newArity);
4986             if (zeroPos == newArity) {
4987                 return 0;
4988             }
4989             return ~zeroPos;
4990         } else {
4991             // same algorithm, different bit set
4992             BitSet mask = new BitSet(newArity);
4993             for (int i = 0; i < reorder.length; i++) {
4994                 int arg = reorder[i];
4995                 if (arg >= newArity) {
4996                     return reorder.length;
4997                 }
4998                 if (mask.get(arg)) {
4999                     return i;  // >0 indicates a dup
5000                 }
5001                 mask.set(arg);
5002             }
5003             int zeroPos = mask.nextClearBit(0);
5004             assert(zeroPos <= newArity);
5005             if (zeroPos == newArity) {
5006                 return 0;
5007             }
5008             return ~zeroPos;
5009         }
5010     }
5011 
5012     static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) {
5013         if (newType.returnType() != oldType.returnType())
5014             throw newIllegalArgumentException("return types do not match",
5015                     oldType, newType);
5016         if (reorder.length != oldType.parameterCount())
5017             throw newIllegalArgumentException("old type parameter count and reorder array length do not match",
5018                     oldType, Arrays.toString(reorder));
5019 
5020         int limit = newType.parameterCount();
5021         for (int j = 0; j < reorder.length; j++) {
5022             int i = reorder[j];
5023             if (i < 0 || i >= limit) {
5024                 throw newIllegalArgumentException("index is out of bounds for new type",
5025                         i, newType);
5026             }
5027             Class<?> src = newType.parameterType(i);
5028             Class<?> dst = oldType.parameterType(j);
5029             if (src != dst)
5030                 throw newIllegalArgumentException("parameter types do not match after reorder",
5031                         oldType, newType);
5032         }
5033         return true;
5034     }
5035 
5036     /**
5037      * Produces a method handle of the requested return type which returns the given
5038      * constant value every time it is invoked.
5039      * <p>
5040      * Before the method handle is returned, the passed-in value is converted to the requested type.
5041      * If the requested type is primitive, widening primitive conversions are attempted,
5042      * else reference conversions are attempted.
5043      * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}.
5044      * @param type the return type of the desired method handle
5045      * @param value the value to return
5046      * @return a method handle of the given return type and no arguments, which always returns the given value
5047      * @throws NullPointerException if the given {@code type} is null, or
5048      *         if the given {@code type} is primitive or a primitive value type
5049      *         and the given value is null
5050      * @throws ClassCastException if the value cannot be converted to the required return type
5051      * @throws IllegalArgumentException if the given type is {@code void.class}
5052      */
5053     public static MethodHandle constant(Class<?> type, Object value) {
5054         if (type.isPrimitive()) {
5055             if (type == void.class)
5056                 throw newIllegalArgumentException("void type");
5057             Wrapper w = Wrapper.forPrimitiveType(type);
5058             value = w.convert(value, type);
5059             if (w.zero().equals(value))
5060                 return zero(w, type);
5061             return insertArguments(identity(type), 0, value);
5062         } else {
5063             if (!type.isPrimitiveValueType() && value == null)
5064                 return zero(Wrapper.OBJECT, type);
5065             return identity(type).bindTo(value);
5066         }
5067     }
5068 
5069     /**
5070      * Produces a method handle which returns its sole argument when invoked.
5071      * @param type the type of the sole parameter and return value of the desired method handle
5072      * @return a unary method handle which accepts and returns the given type
5073      * @throws NullPointerException if the argument is null
5074      * @throws IllegalArgumentException if the given type is {@code void.class}
5075      */
5076     public static MethodHandle identity(Class<?> type) {
5077         Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT);
5078         int pos = btw.ordinal();
5079         MethodHandle ident = IDENTITY_MHS[pos];
5080         if (ident == null) {
5081             ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType()));
5082         }
5083         if (ident.type().returnType() == type)
5084             return ident;
5085         // something like identity(Foo.class); do not bother to intern these
5086         assert (btw == Wrapper.OBJECT);
5087         return makeIdentity(type);
5088     }
5089 
5090     /**
5091      * Produces a constant method handle of the requested return type which
5092      * returns the default value for that type every time it is invoked.
5093      * The resulting constant method handle will have no side effects.
5094      * <p>The returned method handle is equivalent to {@code empty(methodType(type))}.
5095      * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))},
5096      * since {@code explicitCastArguments} converts {@code null} to default values.
5097      * @param type the expected return type of the desired method handle
5098      * @return a constant method handle that takes no arguments
5099      *         and returns the default value of the given type (or void, if the type is void)
5100      * @throws NullPointerException if the argument is null
5101      * @see MethodHandles#constant
5102      * @see MethodHandles#empty
5103      * @see MethodHandles#explicitCastArguments
5104      * @since 9
5105      */
5106     public static MethodHandle zero(Class<?> type) {
5107         Objects.requireNonNull(type);
5108         if (type.isPrimitive()) {
5109             return zero(Wrapper.forPrimitiveType(type), type);
5110         } else if (type.isPrimitiveValueType()) {
5111             // singleton default value
5112             Object value = UNSAFE.uninitializedDefaultValue(type);
5113             return identity(type).bindTo(value);
5114         } else {
5115             return zero(Wrapper.OBJECT, type);
5116         }
5117     }
5118 
5119     private static MethodHandle identityOrVoid(Class<?> type) {
5120         return type == void.class ? zero(type) : identity(type);
5121     }
5122 
5123     /**
5124      * Produces a method handle of the requested type which ignores any arguments, does nothing,
5125      * and returns a suitable default depending on the return type.
5126      * If the requested type is a primitive type or {@code void}, it returns
5127      * a zero primitive value or {@code void}.
5128      * If the requested type is a {@linkplain Class#isPrimitiveValueType() primitive value type},
5129      * it returns a primitive object with the default value.
5130      * If the requested type is a reference type, it returns {@code null}.
5131      * <p>The returned method handle is equivalent to
5132      * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}.
5133      *
5134      * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as
5135      * {@code guardWithTest(pred, target, empty(target.type())}.
5136      * @param type the type of the desired method handle
5137      * @return a constant method handle of the given type, which returns a default value of the given return type
5138      * @throws NullPointerException if the argument is null
5139      * @see MethodHandles#zero
5140      * @see MethodHandles#constant
5141      * @since 9
5142      */
5143     public static  MethodHandle empty(MethodType type) {
5144         Objects.requireNonNull(type);
5145         return dropArguments(zero(type.returnType()), 0, type.parameterList());
5146     }
5147 
5148     private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT];
5149     private static MethodHandle makeIdentity(Class<?> ptype) {
5150         MethodType mtype = MethodType.methodType(ptype, ptype);
5151         LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype));
5152         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY);
5153     }
5154 
5155     private static MethodHandle zero(Wrapper btw, Class<?> rtype) {
5156         int pos = btw.ordinal();
5157         MethodHandle zero = ZERO_MHS[pos];
5158         if (zero == null) {
5159             zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType()));
5160         }
5161         if (zero.type().returnType() == rtype)
5162             return zero;
5163         assert(btw == Wrapper.OBJECT);
5164         return makeZero(rtype);
5165     }
5166     private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT];
5167     private static MethodHandle makeZero(Class<?> rtype) {
5168         MethodType mtype = methodType(rtype);
5169         LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype));
5170         return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO);
5171     }
5172 
5173     private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) {
5174         // Simulate a CAS, to avoid racy duplication of results.
5175         MethodHandle prev = cache[pos];
5176         if (prev != null) return prev;
5177         return cache[pos] = value;
5178     }
5179 
5180     /**
5181      * Provides a target method handle with one or more <em>bound arguments</em>
5182      * in advance of the method handle's invocation.
5183      * The formal parameters to the target corresponding to the bound
5184      * arguments are called <em>bound parameters</em>.
5185      * Returns a new method handle which saves away the bound arguments.
5186      * When it is invoked, it receives arguments for any non-bound parameters,
5187      * binds the saved arguments to their corresponding parameters,
5188      * and calls the original target.
5189      * <p>
5190      * The type of the new method handle will drop the types for the bound
5191      * parameters from the original target type, since the new method handle
5192      * will no longer require those arguments to be supplied by its callers.
5193      * <p>
5194      * Each given argument object must match the corresponding bound parameter type.
5195      * If a bound parameter type is a primitive, the argument object
5196      * must be a wrapper, and will be unboxed to produce the primitive value.
5197      * <p>
5198      * The {@code pos} argument selects which parameters are to be bound.
5199      * It may range between zero and <i>N-L</i> (inclusively),
5200      * where <i>N</i> is the arity of the target method handle
5201      * and <i>L</i> is the length of the values array.
5202      * <p>
5203      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5204      * variable-arity method handle}, even if the original target method handle was.
5205      * @param target the method handle to invoke after the argument is inserted
5206      * @param pos where to insert the argument (zero for the first)
5207      * @param values the series of arguments to insert
5208      * @return a method handle which inserts an additional argument,
5209      *         before calling the original method handle
5210      * @throws NullPointerException if the target or the {@code values} array is null
5211      * @throws IllegalArgumentException if (@code pos) is less than {@code 0} or greater than
5212      *         {@code N - L} where {@code N} is the arity of the target method handle and {@code L}
5213      *         is the length of the values array.
5214      * @throws ClassCastException if an argument does not match the corresponding bound parameter
5215      *         type.
5216      * @see MethodHandle#bindTo
5217      */
5218     public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) {
5219         int insCount = values.length;
5220         Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos);
5221         if (insCount == 0)  return target;
5222         BoundMethodHandle result = target.rebind();
5223         for (int i = 0; i < insCount; i++) {
5224             Object value = values[i];
5225             Class<?> ptype = ptypes[pos+i];
5226             if (ptype.isPrimitive()) {
5227                 result = insertArgumentPrimitive(result, pos, ptype, value);
5228             } else {
5229                 value = ptype.cast(value);  // throw CCE if needed
5230                 result = result.bindArgumentL(pos, value);
5231             }
5232         }
5233         return result;
5234     }
5235 
5236     private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos,
5237                                                              Class<?> ptype, Object value) {
5238         Wrapper w = Wrapper.forPrimitiveType(ptype);
5239         // perform unboxing and/or primitive conversion
5240         value = w.convert(value, ptype);
5241         return switch (w) {
5242             case INT    -> result.bindArgumentI(pos, (int) value);
5243             case LONG   -> result.bindArgumentJ(pos, (long) value);
5244             case FLOAT  -> result.bindArgumentF(pos, (float) value);
5245             case DOUBLE -> result.bindArgumentD(pos, (double) value);
5246             default -> result.bindArgumentI(pos, ValueConversions.widenSubword(value));
5247         };
5248     }
5249 
5250     private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException {
5251         MethodType oldType = target.type();
5252         int outargs = oldType.parameterCount();
5253         int inargs  = outargs - insCount;
5254         if (inargs < 0)
5255             throw newIllegalArgumentException("too many values to insert");
5256         if (pos < 0 || pos > inargs)
5257             throw newIllegalArgumentException("no argument type to append");
5258         return oldType.ptypes();
5259     }
5260 
5261     /**
5262      * Produces a method handle which will discard some dummy arguments
5263      * before calling some other specified <i>target</i> method handle.
5264      * The type of the new method handle will be the same as the target's type,
5265      * except it will also include the dummy argument types,
5266      * at some given position.
5267      * <p>
5268      * The {@code pos} argument may range between zero and <i>N</i>,
5269      * where <i>N</i> is the arity of the target.
5270      * If {@code pos} is zero, the dummy arguments will precede
5271      * the target's real arguments; if {@code pos} is <i>N</i>
5272      * they will come after.
5273      * <p>
5274      * <b>Example:</b>
5275      * <blockquote><pre>{@code
5276 import static java.lang.invoke.MethodHandles.*;
5277 import static java.lang.invoke.MethodType.*;
5278 ...
5279 MethodHandle cat = lookup().findVirtual(String.class,
5280   "concat", methodType(String.class, String.class));
5281 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5282 MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class);
5283 MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2));
5284 assertEquals(bigType, d0.type());
5285 assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z"));
5286      * }</pre></blockquote>
5287      * <p>
5288      * This method is also equivalent to the following code:
5289      * <blockquote><pre>
5290      * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))}
5291      * </pre></blockquote>
5292      * @param target the method handle to invoke after the arguments are dropped
5293      * @param pos position of first argument to drop (zero for the leftmost)
5294      * @param valueTypes the type(s) of the argument(s) to drop
5295      * @return a method handle which drops arguments of the given types,
5296      *         before calling the original method handle
5297      * @throws NullPointerException if the target is null,
5298      *                              or if the {@code valueTypes} list or any of its elements is null
5299      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5300      *                  or if {@code pos} is negative or greater than the arity of the target,
5301      *                  or if the new method handle's type would have too many parameters
5302      */
5303     public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5304         return dropArguments0(target, pos, copyTypes(valueTypes.toArray()));
5305     }
5306 
5307     private static List<Class<?>> copyTypes(Object[] array) {
5308         return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class));
5309     }
5310 
5311     private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
5312         MethodType oldType = target.type();  // get NPE
5313         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
5314         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
5315         if (dropped == 0)  return target;
5316         BoundMethodHandle result = target.rebind();
5317         LambdaForm lform = result.form;
5318         int insertFormArg = 1 + pos;
5319         for (Class<?> ptype : valueTypes) {
5320             lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype));
5321         }
5322         result = result.copyWith(newType, lform);
5323         return result;
5324     }
5325 
5326     private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) {
5327         int dropped = valueTypes.size();
5328         MethodType.checkSlotCount(dropped);
5329         int outargs = oldType.parameterCount();
5330         int inargs  = outargs + dropped;
5331         if (pos < 0 || pos > outargs)
5332             throw newIllegalArgumentException("no argument type to remove"
5333                     + Arrays.asList(oldType, pos, valueTypes, inargs, outargs)
5334                     );
5335         return dropped;
5336     }
5337 
5338     /**
5339      * Produces a method handle which will discard some dummy arguments
5340      * before calling some other specified <i>target</i> method handle.
5341      * The type of the new method handle will be the same as the target's type,
5342      * except it will also include the dummy argument types,
5343      * at some given position.
5344      * <p>
5345      * The {@code pos} argument may range between zero and <i>N</i>,
5346      * where <i>N</i> is the arity of the target.
5347      * If {@code pos} is zero, the dummy arguments will precede
5348      * the target's real arguments; if {@code pos} is <i>N</i>
5349      * they will come after.
5350      * @apiNote
5351      * <blockquote><pre>{@code
5352 import static java.lang.invoke.MethodHandles.*;
5353 import static java.lang.invoke.MethodType.*;
5354 ...
5355 MethodHandle cat = lookup().findVirtual(String.class,
5356   "concat", methodType(String.class, String.class));
5357 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5358 MethodHandle d0 = dropArguments(cat, 0, String.class);
5359 assertEquals("yz", (String) d0.invokeExact("x", "y", "z"));
5360 MethodHandle d1 = dropArguments(cat, 1, String.class);
5361 assertEquals("xz", (String) d1.invokeExact("x", "y", "z"));
5362 MethodHandle d2 = dropArguments(cat, 2, String.class);
5363 assertEquals("xy", (String) d2.invokeExact("x", "y", "z"));
5364 MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class);
5365 assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z"));
5366      * }</pre></blockquote>
5367      * <p>
5368      * This method is also equivalent to the following code:
5369      * <blockquote><pre>
5370      * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))}
5371      * </pre></blockquote>
5372      * @param target the method handle to invoke after the arguments are dropped
5373      * @param pos position of first argument to drop (zero for the leftmost)
5374      * @param valueTypes the type(s) of the argument(s) to drop
5375      * @return a method handle which drops arguments of the given types,
5376      *         before calling the original method handle
5377      * @throws NullPointerException if the target is null,
5378      *                              or if the {@code valueTypes} array or any of its elements is null
5379      * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class},
5380      *                  or if {@code pos} is negative or greater than the arity of the target,
5381      *                  or if the new method handle's type would have
5382      *                  <a href="MethodHandle.html#maxarity">too many parameters</a>
5383      */
5384     public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) {
5385         return dropArguments0(target, pos, copyTypes(valueTypes));
5386     }
5387 
5388     // private version which allows caller some freedom with error handling
5389     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
5390                                       boolean nullOnFailure) {
5391         newTypes = copyTypes(newTypes.toArray());
5392         List<Class<?>> oldTypes = target.type().parameterList();
5393         int match = oldTypes.size();
5394         if (skip != 0) {
5395             if (skip < 0 || skip > match) {
5396                 throw newIllegalArgumentException("illegal skip", skip, target);
5397             }
5398             oldTypes = oldTypes.subList(skip, match);
5399             match -= skip;
5400         }
5401         List<Class<?>> addTypes = newTypes;
5402         int add = addTypes.size();
5403         if (pos != 0) {
5404             if (pos < 0 || pos > add) {
5405                 throw newIllegalArgumentException("illegal pos", pos, newTypes);
5406             }
5407             addTypes = addTypes.subList(pos, add);
5408             add -= pos;
5409             assert(addTypes.size() == add);
5410         }
5411         // Do not add types which already match the existing arguments.
5412         if (match > add || !oldTypes.equals(addTypes.subList(0, match))) {
5413             if (nullOnFailure) {
5414                 return null;
5415             }
5416             throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes);
5417         }
5418         addTypes = addTypes.subList(match, add);
5419         add -= match;
5420         assert(addTypes.size() == add);
5421         // newTypes:     (   P*[pos], M*[match], A*[add] )
5422         // target: ( S*[skip],        M*[match]  )
5423         MethodHandle adapter = target;
5424         if (add > 0) {
5425             adapter = dropArguments0(adapter, skip+ match, addTypes);
5426         }
5427         // adapter: (S*[skip],        M*[match], A*[add] )
5428         if (pos > 0) {
5429             adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
5430         }
5431         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
5432         return adapter;
5433     }
5434 
5435     /**
5436      * Adapts a target method handle to match the given parameter type list. If necessary, adds dummy arguments. Some
5437      * leading parameters can be skipped before matching begins. The remaining types in the {@code target}'s parameter
5438      * type list must be a sub-list of the {@code newTypes} type list at the starting position {@code pos}. The
5439      * resulting handle will have the target handle's parameter type list, with any non-matching parameter types (before
5440      * or after the matching sub-list) inserted in corresponding positions of the target's original parameters, as if by
5441      * {@link #dropArguments(MethodHandle, int, Class[])}.
5442      * <p>
5443      * The resulting handle will have the same return type as the target handle.
5444      * <p>
5445      * In more formal terms, assume these two type lists:<ul>
5446      * <li>The target handle has the parameter type list {@code S..., M...}, with as many types in {@code S} as
5447      * indicated by {@code skip}. The {@code M} types are those that are supposed to match part of the given type list,
5448      * {@code newTypes}.
5449      * <li>The {@code newTypes} list contains types {@code P..., M..., A...}, with as many types in {@code P} as
5450      * indicated by {@code pos}. The {@code M} types are precisely those that the {@code M} types in the target handle's
5451      * parameter type list are supposed to match. The types in {@code A} are additional types found after the matching
5452      * sub-list.
5453      * </ul>
5454      * Given these assumptions, the result of an invocation of {@code dropArgumentsToMatch} will have the parameter type
5455      * list {@code S..., P..., M..., A...}, with the {@code P} and {@code A} types inserted as if by
5456      * {@link #dropArguments(MethodHandle, int, Class[])}.
5457      *
5458      * @apiNote
5459      * Two method handles whose argument lists are "effectively identical" (i.e., identical in a common prefix) may be
5460      * mutually converted to a common type by two calls to {@code dropArgumentsToMatch}, as follows:
5461      * <blockquote><pre>{@code
5462 import static java.lang.invoke.MethodHandles.*;
5463 import static java.lang.invoke.MethodType.*;
5464 ...
5465 ...
5466 MethodHandle h0 = constant(boolean.class, true);
5467 MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class));
5468 MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class);
5469 MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList());
5470 if (h1.type().parameterCount() < h2.type().parameterCount())
5471     h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0);  // lengthen h1
5472 else
5473     h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0);    // lengthen h2
5474 MethodHandle h3 = guardWithTest(h0, h1, h2);
5475 assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c"));
5476      * }</pre></blockquote>
5477      * @param target the method handle to adapt
5478      * @param skip number of targets parameters to disregard (they will be unchanged)
5479      * @param newTypes the list of types to match {@code target}'s parameter type list to
5480      * @param pos place in {@code newTypes} where the non-skipped target parameters must occur
5481      * @return a possibly adapted method handle
5482      * @throws NullPointerException if either argument is null
5483      * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class},
5484      *         or if {@code skip} is negative or greater than the arity of the target,
5485      *         or if {@code pos} is negative or greater than the newTypes list size,
5486      *         or if {@code newTypes} does not contain the {@code target}'s non-skipped parameter types at position
5487      *         {@code pos}.
5488      * @since 9
5489      */
5490     public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) {
5491         Objects.requireNonNull(target);
5492         Objects.requireNonNull(newTypes);
5493         return dropArgumentsToMatch(target, skip, newTypes, pos, false);
5494     }
5495 
5496     /**
5497      * Drop the return value of the target handle (if any).
5498      * The returned method handle will have a {@code void} return type.
5499      *
5500      * @param target the method handle to adapt
5501      * @return a possibly adapted method handle
5502      * @throws NullPointerException if {@code target} is null
5503      * @since 16
5504      */
5505     public static MethodHandle dropReturn(MethodHandle target) {
5506         Objects.requireNonNull(target);
5507         MethodType oldType = target.type();
5508         Class<?> oldReturnType = oldType.returnType();
5509         if (oldReturnType == void.class)
5510             return target;
5511         MethodType newType = oldType.changeReturnType(void.class);
5512         BoundMethodHandle result = target.rebind();
5513         LambdaForm lform = result.editor().filterReturnForm(V_TYPE, true);
5514         result = result.copyWith(newType, lform);
5515         return result;
5516     }
5517 
5518     /**
5519      * Adapts a target method handle by pre-processing
5520      * one or more of its arguments, each with its own unary filter function,
5521      * and then calling the target with each pre-processed argument
5522      * replaced by the result of its corresponding filter function.
5523      * <p>
5524      * The pre-processing is performed by one or more method handles,
5525      * specified in the elements of the {@code filters} array.
5526      * The first element of the filter array corresponds to the {@code pos}
5527      * argument of the target, and so on in sequence.
5528      * The filter functions are invoked in left to right order.
5529      * <p>
5530      * Null arguments in the array are treated as identity functions,
5531      * and the corresponding arguments left unchanged.
5532      * (If there are no non-null elements in the array, the original target is returned.)
5533      * Each filter is applied to the corresponding argument of the adapter.
5534      * <p>
5535      * If a filter {@code F} applies to the {@code N}th argument of
5536      * the target, then {@code F} must be a method handle which
5537      * takes exactly one argument.  The type of {@code F}'s sole argument
5538      * replaces the corresponding argument type of the target
5539      * in the resulting adapted method handle.
5540      * The return type of {@code F} must be identical to the corresponding
5541      * parameter type of the target.
5542      * <p>
5543      * It is an error if there are elements of {@code filters}
5544      * (null or not)
5545      * which do not correspond to argument positions in the target.
5546      * <p><b>Example:</b>
5547      * <blockquote><pre>{@code
5548 import static java.lang.invoke.MethodHandles.*;
5549 import static java.lang.invoke.MethodType.*;
5550 ...
5551 MethodHandle cat = lookup().findVirtual(String.class,
5552   "concat", methodType(String.class, String.class));
5553 MethodHandle upcase = lookup().findVirtual(String.class,
5554   "toUpperCase", methodType(String.class));
5555 assertEquals("xy", (String) cat.invokeExact("x", "y"));
5556 MethodHandle f0 = filterArguments(cat, 0, upcase);
5557 assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy
5558 MethodHandle f1 = filterArguments(cat, 1, upcase);
5559 assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY
5560 MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
5561 assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY
5562      * }</pre></blockquote>
5563      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5564      * denotes the return type of both the {@code target} and resulting adapter.
5565      * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values
5566      * of the parameters and arguments that precede and follow the filter position
5567      * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and
5568      * values of the filtered parameters and arguments; they also represent the
5569      * return types of the {@code filter[i]} handles. The latter accept arguments
5570      * {@code v[i]} of type {@code V[i]}, which also appear in the signature of
5571      * the resulting adapter.
5572      * <blockquote><pre>{@code
5573      * T target(P... p, A[i]... a[i], B... b);
5574      * A[i] filter[i](V[i]);
5575      * T adapter(P... p, V[i]... v[i], B... b) {
5576      *   return target(p..., filter[i](v[i])..., b...);
5577      * }
5578      * }</pre></blockquote>
5579      * <p>
5580      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5581      * variable-arity method handle}, even if the original target method handle was.
5582      *
5583      * @param target the method handle to invoke after arguments are filtered
5584      * @param pos the position of the first argument to filter
5585      * @param filters method handles to call initially on filtered arguments
5586      * @return method handle which incorporates the specified argument filtering logic
5587      * @throws NullPointerException if the target is null
5588      *                              or if the {@code filters} array is null
5589      * @throws IllegalArgumentException if a non-null element of {@code filters}
5590      *          does not match a corresponding argument type of target as described above,
5591      *          or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()},
5592      *          or if the resulting method handle's type would have
5593      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5594      */
5595     public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) {
5596         // In method types arguments start at index 0, while the LF
5597         // editor have the MH receiver at position 0 - adjust appropriately.
5598         final int MH_RECEIVER_OFFSET = 1;
5599         filterArgumentsCheckArity(target, pos, filters);
5600         MethodHandle adapter = target;
5601 
5602         // keep track of currently matched filters, as to optimize repeated filters
5603         int index = 0;
5604         int[] positions = new int[filters.length];
5605         MethodHandle filter = null;
5606 
5607         // process filters in reverse order so that the invocation of
5608         // the resulting adapter will invoke the filters in left-to-right order
5609         for (int i = filters.length - 1; i >= 0; --i) {
5610             MethodHandle newFilter = filters[i];
5611             if (newFilter == null) continue;  // ignore null elements of filters
5612 
5613             // flush changes on update
5614             if (filter != newFilter) {
5615                 if (filter != null) {
5616                     if (index > 1) {
5617                         adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5618                     } else {
5619                         adapter = filterArgument(adapter, positions[0] - 1, filter);
5620                     }
5621                 }
5622                 filter = newFilter;
5623                 index = 0;
5624             }
5625 
5626             filterArgumentChecks(target, pos + i, newFilter);
5627             positions[index++] = pos + i + MH_RECEIVER_OFFSET;
5628         }
5629         if (index > 1) {
5630             adapter = filterRepeatedArgument(adapter, filter, Arrays.copyOf(positions, index));
5631         } else if (index == 1) {
5632             adapter = filterArgument(adapter, positions[0] - 1, filter);
5633         }
5634         return adapter;
5635     }
5636 
5637     private static MethodHandle filterRepeatedArgument(MethodHandle adapter, MethodHandle filter, int[] positions) {
5638         MethodType targetType = adapter.type();
5639         MethodType filterType = filter.type();
5640         BoundMethodHandle result = adapter.rebind();
5641         Class<?> newParamType = filterType.parameterType(0);
5642 
5643         Class<?>[] ptypes = targetType.ptypes().clone();
5644         for (int pos : positions) {
5645             ptypes[pos - 1] = newParamType;
5646         }
5647         MethodType newType = MethodType.makeImpl(targetType.rtype(), ptypes, true);
5648 
5649         LambdaForm lform = result.editor().filterRepeatedArgumentForm(BasicType.basicType(newParamType), positions);
5650         return result.copyWithExtendL(newType, lform, filter);
5651     }
5652 
5653     /*non-public*/
5654     static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) {
5655         filterArgumentChecks(target, pos, filter);
5656         MethodType targetType = target.type();
5657         MethodType filterType = filter.type();
5658         BoundMethodHandle result = target.rebind();
5659         Class<?> newParamType = filterType.parameterType(0);
5660         LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType));
5661         MethodType newType = targetType.changeParameterType(pos, newParamType);
5662         result = result.copyWithExtendL(newType, lform, filter);
5663         return result;
5664     }
5665 
5666     private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) {
5667         MethodType targetType = target.type();
5668         int maxPos = targetType.parameterCount();
5669         if (pos + filters.length > maxPos)
5670             throw newIllegalArgumentException("too many filters");
5671     }
5672 
5673     private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5674         MethodType targetType = target.type();
5675         MethodType filterType = filter.type();
5676         if (filterType.parameterCount() != 1
5677             || filterType.returnType() != targetType.parameterType(pos))
5678             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5679     }
5680 
5681     /**
5682      * Adapts a target method handle by pre-processing
5683      * a sub-sequence of its arguments with a filter (another method handle).
5684      * The pre-processed arguments are replaced by the result (if any) of the
5685      * filter function.
5686      * The target is then called on the modified (usually shortened) argument list.
5687      * <p>
5688      * If the filter returns a value, the target must accept that value as
5689      * its argument in position {@code pos}, preceded and/or followed by
5690      * any arguments not passed to the filter.
5691      * If the filter returns void, the target must accept all arguments
5692      * not passed to the filter.
5693      * No arguments are reordered, and a result returned from the filter
5694      * replaces (in order) the whole subsequence of arguments originally
5695      * passed to the adapter.
5696      * <p>
5697      * The argument types (if any) of the filter
5698      * replace zero or one argument types of the target, at position {@code pos},
5699      * in the resulting adapted method handle.
5700      * The return type of the filter (if any) must be identical to the
5701      * argument type of the target at position {@code pos}, and that target argument
5702      * is supplied by the return value of the filter.
5703      * <p>
5704      * In all cases, {@code pos} must be greater than or equal to zero, and
5705      * {@code pos} must also be less than or equal to the target's arity.
5706      * <p><b>Example:</b>
5707      * <blockquote><pre>{@code
5708 import static java.lang.invoke.MethodHandles.*;
5709 import static java.lang.invoke.MethodType.*;
5710 ...
5711 MethodHandle deepToString = publicLookup()
5712   .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
5713 
5714 MethodHandle ts1 = deepToString.asCollector(String[].class, 1);
5715 assertEquals("[strange]", (String) ts1.invokeExact("strange"));
5716 
5717 MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
5718 assertEquals("[up, down]", (String) ts2.invokeExact("up", "down"));
5719 
5720 MethodHandle ts3 = deepToString.asCollector(String[].class, 3);
5721 MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2);
5722 assertEquals("[top, [up, down], strange]",
5723              (String) ts3_ts2.invokeExact("top", "up", "down", "strange"));
5724 
5725 MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1);
5726 assertEquals("[top, [up, down], [strange]]",
5727              (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange"));
5728 
5729 MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3);
5730 assertEquals("[top, [[up, down, strange], charm], bottom]",
5731              (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom"));
5732      * }</pre></blockquote>
5733      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5734      * represents the return type of the {@code target} and resulting adapter.
5735      * {@code V}/{@code v} stand for the return type and value of the
5736      * {@code filter}, which are also found in the signature and arguments of
5737      * the {@code target}, respectively, unless {@code V} is {@code void}.
5738      * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types
5739      * and values preceding and following the collection position, {@code pos},
5740      * in the {@code target}'s signature. They also turn up in the resulting
5741      * adapter's signature and arguments, where they surround
5742      * {@code B}/{@code b}, which represent the parameter types and arguments
5743      * to the {@code filter} (if any).
5744      * <blockquote><pre>{@code
5745      * T target(A...,V,C...);
5746      * V filter(B...);
5747      * T adapter(A... a,B... b,C... c) {
5748      *   V v = filter(b...);
5749      *   return target(a...,v,c...);
5750      * }
5751      * // and if the filter has no arguments:
5752      * T target2(A...,V,C...);
5753      * V filter2();
5754      * T adapter2(A... a,C... c) {
5755      *   V v = filter2();
5756      *   return target2(a...,v,c...);
5757      * }
5758      * // and if the filter has a void return:
5759      * T target3(A...,C...);
5760      * void filter3(B...);
5761      * T adapter3(A... a,B... b,C... c) {
5762      *   filter3(b...);
5763      *   return target3(a...,c...);
5764      * }
5765      * }</pre></blockquote>
5766      * <p>
5767      * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to
5768      * one which first "folds" the affected arguments, and then drops them, in separate
5769      * steps as follows:
5770      * <blockquote><pre>{@code
5771      * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2
5772      * mh = MethodHandles.foldArguments(mh, coll); //step 1
5773      * }</pre></blockquote>
5774      * If the target method handle consumes no arguments besides than the result
5775      * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)}
5776      * is equivalent to {@code filterReturnValue(coll, mh)}.
5777      * If the filter method handle {@code coll} consumes one argument and produces
5778      * a non-void result, then {@code collectArguments(mh, N, coll)}
5779      * is equivalent to {@code filterArguments(mh, N, coll)}.
5780      * Other equivalences are possible but would require argument permutation.
5781      * <p>
5782      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5783      * variable-arity method handle}, even if the original target method handle was.
5784      *
5785      * @param target the method handle to invoke after filtering the subsequence of arguments
5786      * @param pos the position of the first adapter argument to pass to the filter,
5787      *            and/or the target argument which receives the result of the filter
5788      * @param filter method handle to call on the subsequence of arguments
5789      * @return method handle which incorporates the specified argument subsequence filtering logic
5790      * @throws NullPointerException if either argument is null
5791      * @throws IllegalArgumentException if the return type of {@code filter}
5792      *          is non-void and is not the same as the {@code pos} argument of the target,
5793      *          or if {@code pos} is not between 0 and the target's arity, inclusive,
5794      *          or if the resulting method handle's type would have
5795      *          <a href="MethodHandle.html#maxarity">too many parameters</a>
5796      * @see MethodHandles#foldArguments
5797      * @see MethodHandles#filterArguments
5798      * @see MethodHandles#filterReturnValue
5799      */
5800     public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) {
5801         MethodType newType = collectArgumentsChecks(target, pos, filter);
5802         MethodType collectorType = filter.type();
5803         BoundMethodHandle result = target.rebind();
5804         LambdaForm lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType());
5805         return result.copyWithExtendL(newType, lform, filter);
5806     }
5807 
5808     private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException {
5809         MethodType targetType = target.type();
5810         MethodType filterType = filter.type();
5811         Class<?> rtype = filterType.returnType();
5812         List<Class<?>> filterArgs = filterType.parameterList();
5813         if (pos < 0 || (rtype == void.class && pos > targetType.parameterCount()) ||
5814                        (rtype != void.class && pos >= targetType.parameterCount())) {
5815             throw newIllegalArgumentException("position is out of range for target", target, pos);
5816         }
5817         if (rtype == void.class) {
5818             return targetType.insertParameterTypes(pos, filterArgs);
5819         }
5820         if (rtype != targetType.parameterType(pos)) {
5821             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5822         }
5823         return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs);
5824     }
5825 
5826     /**
5827      * Adapts a target method handle by post-processing
5828      * its return value (if any) with a filter (another method handle).
5829      * The result of the filter is returned from the adapter.
5830      * <p>
5831      * If the target returns a value, the filter must accept that value as
5832      * its only argument.
5833      * If the target returns void, the filter must accept no arguments.
5834      * <p>
5835      * The return type of the filter
5836      * replaces the return type of the target
5837      * in the resulting adapted method handle.
5838      * The argument type of the filter (if any) must be identical to the
5839      * return type of the target.
5840      * <p><b>Example:</b>
5841      * <blockquote><pre>{@code
5842 import static java.lang.invoke.MethodHandles.*;
5843 import static java.lang.invoke.MethodType.*;
5844 ...
5845 MethodHandle cat = lookup().findVirtual(String.class,
5846   "concat", methodType(String.class, String.class));
5847 MethodHandle length = lookup().findVirtual(String.class,
5848   "length", methodType(int.class));
5849 System.out.println((String) cat.invokeExact("x", "y")); // xy
5850 MethodHandle f0 = filterReturnValue(cat, length);
5851 System.out.println((int) f0.invokeExact("x", "y")); // 2
5852      * }</pre></blockquote>
5853      * <p>Here is pseudocode for the resulting adapter. In the code,
5854      * {@code T}/{@code t} represent the result type and value of the
5855      * {@code target}; {@code V}, the result type of the {@code filter}; and
5856      * {@code A}/{@code a}, the types and values of the parameters and arguments
5857      * of the {@code target} as well as the resulting adapter.
5858      * <blockquote><pre>{@code
5859      * T target(A...);
5860      * V filter(T);
5861      * V adapter(A... a) {
5862      *   T t = target(a...);
5863      *   return filter(t);
5864      * }
5865      * // and if the target has a void return:
5866      * void target2(A...);
5867      * V filter2();
5868      * V adapter2(A... a) {
5869      *   target2(a...);
5870      *   return filter2();
5871      * }
5872      * // and if the filter has a void return:
5873      * T target3(A...);
5874      * void filter3(V);
5875      * void adapter3(A... a) {
5876      *   T t = target3(a...);
5877      *   filter3(t);
5878      * }
5879      * }</pre></blockquote>
5880      * <p>
5881      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
5882      * variable-arity method handle}, even if the original target method handle was.
5883      * @param target the method handle to invoke before filtering the return value
5884      * @param filter method handle to call on the return value
5885      * @return method handle which incorporates the specified return value filtering logic
5886      * @throws NullPointerException if either argument is null
5887      * @throws IllegalArgumentException if the argument list of {@code filter}
5888      *          does not match the return type of target as described above
5889      */
5890     public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
5891         MethodType targetType = target.type();
5892         MethodType filterType = filter.type();
5893         filterReturnValueChecks(targetType, filterType);
5894         BoundMethodHandle result = target.rebind();
5895         BasicType rtype = BasicType.basicType(filterType.returnType());
5896         LambdaForm lform = result.editor().filterReturnForm(rtype, false);
5897         MethodType newType = targetType.changeReturnType(filterType.returnType());
5898         result = result.copyWithExtendL(newType, lform, filter);
5899         return result;
5900     }
5901 
5902     private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException {
5903         Class<?> rtype = targetType.returnType();
5904         int filterValues = filterType.parameterCount();
5905         if (filterValues == 0
5906                 ? (rtype != void.class)
5907                 : (rtype != filterType.parameterType(0) || filterValues != 1))
5908             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
5909     }
5910 
5911     /**
5912      * Filter the return value of a target method handle with a filter function. The filter function is
5913      * applied to the return value of the original handle; if the filter specifies more than one parameters,
5914      * then any remaining parameter is appended to the adapter handle. In other words, the adaptation works
5915      * as follows:
5916      * <blockquote><pre>{@code
5917      * T target(A...)
5918      * V filter(B... , T)
5919      * V adapter(A... a, B... b) {
5920      *     T t = target(a...);
5921      *     return filter(b..., t);
5922      * }</pre></blockquote>
5923      * <p>
5924      * If the filter handle is a unary function, then this method behaves like {@link #filterReturnValue(MethodHandle, MethodHandle)}.
5925      *
5926      * @param target the target method handle
5927      * @param filter the filter method handle
5928      * @return the adapter method handle
5929      */
5930     /* package */ static MethodHandle collectReturnValue(MethodHandle target, MethodHandle filter) {
5931         MethodType targetType = target.type();
5932         MethodType filterType = filter.type();
5933         BoundMethodHandle result = target.rebind();
5934         LambdaForm lform = result.editor().collectReturnValueForm(filterType.basicType());
5935         MethodType newType = targetType.changeReturnType(filterType.returnType());
5936         if (filterType.parameterCount() > 1) {
5937             for (int i = 0 ; i < filterType.parameterCount() - 1 ; i++) {
5938                 newType = newType.appendParameterTypes(filterType.parameterType(i));
5939             }
5940         }
5941         result = result.copyWithExtendL(newType, lform, filter);
5942         return result;
5943     }
5944 
5945     /**
5946      * Adapts a target method handle by pre-processing
5947      * some of its arguments, and then calling the target with
5948      * the result of the pre-processing, inserted into the original
5949      * sequence of arguments.
5950      * <p>
5951      * The pre-processing is performed by {@code combiner}, a second method handle.
5952      * Of the arguments passed to the adapter, the first {@code N} arguments
5953      * are copied to the combiner, which is then called.
5954      * (Here, {@code N} is defined as the parameter count of the combiner.)
5955      * After this, control passes to the target, with any result
5956      * from the combiner inserted before the original {@code N} incoming
5957      * arguments.
5958      * <p>
5959      * If the combiner returns a value, the first parameter type of the target
5960      * must be identical with the return type of the combiner, and the next
5961      * {@code N} parameter types of the target must exactly match the parameters
5962      * of the combiner.
5963      * <p>
5964      * If the combiner has a void return, no result will be inserted,
5965      * and the first {@code N} parameter types of the target
5966      * must exactly match the parameters of the combiner.
5967      * <p>
5968      * The resulting adapter is the same type as the target, except that the
5969      * first parameter type is dropped,
5970      * if it corresponds to the result of the combiner.
5971      * <p>
5972      * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments
5973      * that either the combiner or the target does not wish to receive.
5974      * If some of the incoming arguments are destined only for the combiner,
5975      * consider using {@link MethodHandle#asCollector asCollector} instead, since those
5976      * arguments will not need to be live on the stack on entry to the
5977      * target.)
5978      * <p><b>Example:</b>
5979      * <blockquote><pre>{@code
5980 import static java.lang.invoke.MethodHandles.*;
5981 import static java.lang.invoke.MethodType.*;
5982 ...
5983 MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
5984   "println", methodType(void.class, String.class))
5985     .bindTo(System.out);
5986 MethodHandle cat = lookup().findVirtual(String.class,
5987   "concat", methodType(String.class, String.class));
5988 assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
5989 MethodHandle catTrace = foldArguments(cat, trace);
5990 // also prints "boo":
5991 assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
5992      * }</pre></blockquote>
5993      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
5994      * represents the result type of the {@code target} and resulting adapter.
5995      * {@code V}/{@code v} represent the type and value of the parameter and argument
5996      * of {@code target} that precedes the folding position; {@code V} also is
5997      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
5998      * types and values of the {@code N} parameters and arguments at the folding
5999      * position. {@code B}/{@code b} represent the types and values of the
6000      * {@code target} parameters and arguments that follow the folded parameters
6001      * and arguments.
6002      * <blockquote><pre>{@code
6003      * // there are N arguments in A...
6004      * T target(V, A[N]..., B...);
6005      * V combiner(A...);
6006      * T adapter(A... a, B... b) {
6007      *   V v = combiner(a...);
6008      *   return target(v, a..., b...);
6009      * }
6010      * // and if the combiner has a void return:
6011      * T target2(A[N]..., B...);
6012      * void combiner2(A...);
6013      * T adapter2(A... a, B... b) {
6014      *   combiner2(a...);
6015      *   return target2(a..., b...);
6016      * }
6017      * }</pre></blockquote>
6018      * <p>
6019      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6020      * variable-arity method handle}, even if the original target method handle was.
6021      * @param target the method handle to invoke after arguments are combined
6022      * @param combiner method handle to call initially on the incoming arguments
6023      * @return method handle which incorporates the specified argument folding logic
6024      * @throws NullPointerException if either argument is null
6025      * @throws IllegalArgumentException if {@code combiner}'s return type
6026      *          is non-void and not the same as the first argument type of
6027      *          the target, or if the initial {@code N} argument types
6028      *          of the target
6029      *          (skipping one matching the {@code combiner}'s return type)
6030      *          are not identical with the argument types of {@code combiner}
6031      */
6032     public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) {
6033         return foldArguments(target, 0, combiner);
6034     }
6035 
6036     /**
6037      * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then
6038      * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just
6039      * before the folded arguments.
6040      * <p>
6041      * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the
6042      * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a
6043      * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position
6044      * 0.
6045      *
6046      * @apiNote Example:
6047      * <blockquote><pre>{@code
6048     import static java.lang.invoke.MethodHandles.*;
6049     import static java.lang.invoke.MethodType.*;
6050     ...
6051     MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class,
6052     "println", methodType(void.class, String.class))
6053     .bindTo(System.out);
6054     MethodHandle cat = lookup().findVirtual(String.class,
6055     "concat", methodType(String.class, String.class));
6056     assertEquals("boojum", (String) cat.invokeExact("boo", "jum"));
6057     MethodHandle catTrace = foldArguments(cat, 1, trace);
6058     // also prints "jum":
6059     assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum"));
6060      * }</pre></blockquote>
6061      * <p>Here is pseudocode for the resulting adapter. In the code, {@code T}
6062      * represents the result type of the {@code target} and resulting adapter.
6063      * {@code V}/{@code v} represent the type and value of the parameter and argument
6064      * of {@code target} that precedes the folding position; {@code V} also is
6065      * the result type of the {@code combiner}. {@code A}/{@code a} denote the
6066      * types and values of the {@code N} parameters and arguments at the folding
6067      * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types
6068      * and values of the {@code target} parameters and arguments that precede and
6069      * follow the folded parameters and arguments starting at {@code pos},
6070      * respectively.
6071      * <blockquote><pre>{@code
6072      * // there are N arguments in A...
6073      * T target(Z..., V, A[N]..., B...);
6074      * V combiner(A...);
6075      * T adapter(Z... z, A... a, B... b) {
6076      *   V v = combiner(a...);
6077      *   return target(z..., v, a..., b...);
6078      * }
6079      * // and if the combiner has a void return:
6080      * T target2(Z..., A[N]..., B...);
6081      * void combiner2(A...);
6082      * T adapter2(Z... z, A... a, B... b) {
6083      *   combiner2(a...);
6084      *   return target2(z..., a..., b...);
6085      * }
6086      * }</pre></blockquote>
6087      * <p>
6088      * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector
6089      * variable-arity method handle}, even if the original target method handle was.
6090      *
6091      * @param target the method handle to invoke after arguments are combined
6092      * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code
6093      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6094      * @param combiner method handle to call initially on the incoming arguments
6095      * @return method handle which incorporates the specified argument folding logic
6096      * @throws NullPointerException if either argument is null
6097      * @throws IllegalArgumentException if either of the following two conditions holds:
6098      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6099      *              {@code pos} of the target signature;
6100      *          (2) the {@code N} argument types at position {@code pos} of the target signature (skipping one matching
6101      *              the {@code combiner}'s return type) are not identical with the argument types of {@code combiner}.
6102      *
6103      * @see #foldArguments(MethodHandle, MethodHandle)
6104      * @since 9
6105      */
6106     public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) {
6107         MethodType targetType = target.type();
6108         MethodType combinerType = combiner.type();
6109         Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType);
6110         BoundMethodHandle result = target.rebind();
6111         boolean dropResult = rtype == void.class;
6112         LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType());
6113         MethodType newType = targetType;
6114         if (!dropResult) {
6115             newType = newType.dropParameterTypes(pos, pos + 1);
6116         }
6117         result = result.copyWithExtendL(newType, lform, combiner);
6118         return result;
6119     }
6120 
6121     private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) {
6122         int foldArgs   = combinerType.parameterCount();
6123         Class<?> rtype = combinerType.returnType();
6124         int foldVals = rtype == void.class ? 0 : 1;
6125         int afterInsertPos = foldPos + foldVals;
6126         boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs);
6127         if (ok) {
6128             for (int i = 0; i < foldArgs; i++) {
6129                 if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) {
6130                     ok = false;
6131                     break;
6132                 }
6133             }
6134         }
6135         if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos))
6136             ok = false;
6137         if (!ok)
6138             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6139         return rtype;
6140     }
6141 
6142     /**
6143      * Adapts a target method handle by pre-processing some of its arguments, then calling the target with the result
6144      * of the pre-processing replacing the argument at the given position.
6145      *
6146      * @param target the method handle to invoke after arguments are combined
6147      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6148      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6149      * @param combiner method handle to call initially on the incoming arguments
6150      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6151      * @return method handle which incorporates the specified argument folding logic
6152      * @throws NullPointerException if either argument is null
6153      * @throws IllegalArgumentException if either of the following two conditions holds:
6154      *          (1) {@code combiner}'s return type is not the same as the argument type at position
6155      *              {@code pos} of the target signature;
6156      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature are
6157      *              not identical with the argument types of {@code combiner}.
6158      */
6159     /*non-public*/
6160     static MethodHandle filterArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6161         return argumentsWithCombiner(true, target, position, combiner, argPositions);
6162     }
6163 
6164     /**
6165      * Adapts a target method handle by pre-processing some of its arguments, calling the target with the result of
6166      * the pre-processing inserted into the original sequence of arguments at the given position.
6167      *
6168      * @param target the method handle to invoke after arguments are combined
6169      * @param position the position at which to start folding and at which to insert the folding result; if this is {@code
6170      *            0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}.
6171      * @param combiner method handle to call initially on the incoming arguments
6172      * @param argPositions indexes of the target to pick arguments sent to the combiner from
6173      * @return method handle which incorporates the specified argument folding logic
6174      * @throws NullPointerException if either argument is null
6175      * @throws IllegalArgumentException if either of the following two conditions holds:
6176      *          (1) {@code combiner}'s return type is non-{@code void} and not the same as the argument type at position
6177      *              {@code pos} of the target signature;
6178      *          (2) the {@code N} argument types at positions {@code argPositions[1...N]} of the target signature
6179      *              (skipping {@code position} where the {@code combiner}'s return will be folded in) are not identical
6180      *              with the argument types of {@code combiner}.
6181      */
6182     /*non-public*/
6183     static MethodHandle foldArgumentsWithCombiner(MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6184         return argumentsWithCombiner(false, target, position, combiner, argPositions);
6185     }
6186 
6187     private static MethodHandle argumentsWithCombiner(boolean filter, MethodHandle target, int position, MethodHandle combiner, int ... argPositions) {
6188         MethodType targetType = target.type();
6189         MethodType combinerType = combiner.type();
6190         Class<?> rtype = argumentsWithCombinerChecks(position, filter, targetType, combinerType, argPositions);
6191         BoundMethodHandle result = target.rebind();
6192 
6193         MethodType newType = targetType;
6194         LambdaForm lform;
6195         if (filter) {
6196             lform = result.editor().filterArgumentsForm(1 + position, combinerType.basicType(), argPositions);
6197         } else {
6198             boolean dropResult = rtype == void.class;
6199             lform = result.editor().foldArgumentsForm(1 + position, dropResult, combinerType.basicType(), argPositions);
6200             if (!dropResult) {
6201                 newType = newType.dropParameterTypes(position, position + 1);
6202             }
6203         }
6204         result = result.copyWithExtendL(newType, lform, combiner);
6205         return result;
6206     }
6207 
6208     private static Class<?> argumentsWithCombinerChecks(int position, boolean filter, MethodType targetType, MethodType combinerType, int ... argPos) {
6209         int combinerArgs = combinerType.parameterCount();
6210         if (argPos.length != combinerArgs) {
6211             throw newIllegalArgumentException("combiner and argument map must be equal size", combinerType, argPos.length);
6212         }
6213         Class<?> rtype = combinerType.returnType();
6214 
6215         for (int i = 0; i < combinerArgs; i++) {
6216             int arg = argPos[i];
6217             if (arg < 0 || arg > targetType.parameterCount()) {
6218                 throw newIllegalArgumentException("arg outside of target parameterRange", targetType, arg);
6219             }
6220             if (combinerType.parameterType(i) != targetType.parameterType(arg)) {
6221                 throw newIllegalArgumentException("target argument type at position " + arg
6222                         + " must match combiner argument type at index " + i + ": " + targetType
6223                         + " -> " + combinerType + ", map: " + Arrays.toString(argPos));
6224             }
6225         }
6226         if (filter && combinerType.returnType() != targetType.parameterType(position)) {
6227             throw misMatchedTypes("target and combiner types", targetType, combinerType);
6228         }
6229         return rtype;
6230     }
6231 
6232     /**
6233      * Makes a method handle which adapts a target method handle,
6234      * by guarding it with a test, a boolean-valued method handle.
6235      * If the guard fails, a fallback handle is called instead.
6236      * All three method handles must have the same corresponding
6237      * argument and return types, except that the return type
6238      * of the test must be boolean, and the test is allowed
6239      * to have fewer arguments than the other two method handles.
6240      * <p>
6241      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6242      * represents the uniform result type of the three involved handles;
6243      * {@code A}/{@code a}, the types and values of the {@code target}
6244      * parameters and arguments that are consumed by the {@code test}; and
6245      * {@code B}/{@code b}, those types and values of the {@code target}
6246      * parameters and arguments that are not consumed by the {@code test}.
6247      * <blockquote><pre>{@code
6248      * boolean test(A...);
6249      * T target(A...,B...);
6250      * T fallback(A...,B...);
6251      * T adapter(A... a,B... b) {
6252      *   if (test(a...))
6253      *     return target(a..., b...);
6254      *   else
6255      *     return fallback(a..., b...);
6256      * }
6257      * }</pre></blockquote>
6258      * Note that the test arguments ({@code a...} in the pseudocode) cannot
6259      * be modified by execution of the test, and so are passed unchanged
6260      * from the caller to the target or fallback as appropriate.
6261      * @param test method handle used for test, must return boolean
6262      * @param target method handle to call if test passes
6263      * @param fallback method handle to call if test fails
6264      * @return method handle which incorporates the specified if/then/else logic
6265      * @throws NullPointerException if any argument is null
6266      * @throws IllegalArgumentException if {@code test} does not return boolean,
6267      *          or if all three method types do not match (with the return
6268      *          type of {@code test} changed to match that of the target).
6269      */
6270     public static MethodHandle guardWithTest(MethodHandle test,
6271                                MethodHandle target,
6272                                MethodHandle fallback) {
6273         MethodType gtype = test.type();
6274         MethodType ttype = target.type();
6275         MethodType ftype = fallback.type();
6276         if (!ttype.equals(ftype))
6277             throw misMatchedTypes("target and fallback types", ttype, ftype);
6278         if (gtype.returnType() != boolean.class)
6279             throw newIllegalArgumentException("guard type is not a predicate "+gtype);
6280         List<Class<?>> targs = ttype.parameterList();
6281         test = dropArgumentsToMatch(test, 0, targs, 0, true);
6282         if (test == null) {
6283             throw misMatchedTypes("target and test types", ttype, gtype);
6284         }
6285         return MethodHandleImpl.makeGuardWithTest(test, target, fallback);
6286     }
6287 
6288     static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) {
6289         return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2);
6290     }
6291 
6292     /**
6293      * Makes a method handle which adapts a target method handle,
6294      * by running it inside an exception handler.
6295      * If the target returns normally, the adapter returns that value.
6296      * If an exception matching the specified type is thrown, the fallback
6297      * handle is called instead on the exception, plus the original arguments.
6298      * <p>
6299      * The target and handler must have the same corresponding
6300      * argument and return types, except that handler may omit trailing arguments
6301      * (similarly to the predicate in {@link #guardWithTest guardWithTest}).
6302      * Also, the handler must have an extra leading parameter of {@code exType} or a supertype.
6303      * <p>
6304      * Here is pseudocode for the resulting adapter. In the code, {@code T}
6305      * represents the return type of the {@code target} and {@code handler},
6306      * and correspondingly that of the resulting adapter; {@code A}/{@code a},
6307      * the types and values of arguments to the resulting handle consumed by
6308      * {@code handler}; and {@code B}/{@code b}, those of arguments to the
6309      * resulting handle discarded by {@code handler}.
6310      * <blockquote><pre>{@code
6311      * T target(A..., B...);
6312      * T handler(ExType, A...);
6313      * T adapter(A... a, B... b) {
6314      *   try {
6315      *     return target(a..., b...);
6316      *   } catch (ExType ex) {
6317      *     return handler(ex, a...);
6318      *   }
6319      * }
6320      * }</pre></blockquote>
6321      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
6322      * be modified by execution of the target, and so are passed unchanged
6323      * from the caller to the handler, if the handler is invoked.
6324      * <p>
6325      * The target and handler must return the same type, even if the handler
6326      * always throws.  (This might happen, for instance, because the handler
6327      * is simulating a {@code finally} clause).
6328      * To create such a throwing handler, compose the handler creation logic
6329      * with {@link #throwException throwException},
6330      * in order to create a method handle of the correct return type.
6331      * @param target method handle to call
6332      * @param exType the type of exception which the handler will catch
6333      * @param handler method handle to call if a matching exception is thrown
6334      * @return method handle which incorporates the specified try/catch logic
6335      * @throws NullPointerException if any argument is null
6336      * @throws IllegalArgumentException if {@code handler} does not accept
6337      *          the given exception type, or if the method handle types do
6338      *          not match in their return types and their
6339      *          corresponding parameters
6340      * @see MethodHandles#tryFinally(MethodHandle, MethodHandle)
6341      */
6342     public static MethodHandle catchException(MethodHandle target,
6343                                 Class<? extends Throwable> exType,
6344                                 MethodHandle handler) {
6345         MethodType ttype = target.type();
6346         MethodType htype = handler.type();
6347         if (!Throwable.class.isAssignableFrom(exType))
6348             throw new ClassCastException(exType.getName());
6349         if (htype.parameterCount() < 1 ||
6350             !htype.parameterType(0).isAssignableFrom(exType))
6351             throw newIllegalArgumentException("handler does not accept exception type "+exType);
6352         if (htype.returnType() != ttype.returnType())
6353             throw misMatchedTypes("target and handler return types", ttype, htype);
6354         handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true);
6355         if (handler == null) {
6356             throw misMatchedTypes("target and handler types", ttype, htype);
6357         }
6358         return MethodHandleImpl.makeGuardWithCatch(target, exType, handler);
6359     }
6360 
6361     /**
6362      * Produces a method handle which will throw exceptions of the given {@code exType}.
6363      * The method handle will accept a single argument of {@code exType},
6364      * and immediately throw it as an exception.
6365      * The method type will nominally specify a return of {@code returnType}.
6366      * The return type may be anything convenient:  It doesn't matter to the
6367      * method handle's behavior, since it will never return normally.
6368      * @param returnType the return type of the desired method handle
6369      * @param exType the parameter type of the desired method handle
6370      * @return method handle which can throw the given exceptions
6371      * @throws NullPointerException if either argument is null
6372      */
6373     public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) {
6374         if (!Throwable.class.isAssignableFrom(exType))
6375             throw new ClassCastException(exType.getName());
6376         return MethodHandleImpl.throwException(methodType(returnType, exType));
6377     }
6378 
6379     /**
6380      * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each
6381      * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and
6382      * delivers the loop's result, which is the return value of the resulting handle.
6383      * <p>
6384      * Intuitively, every loop is formed by one or more "clauses", each specifying a local <em>iteration variable</em> and/or a loop
6385      * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration
6386      * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in
6387      * terms of method handles, each clause will specify up to four independent actions:<ul>
6388      * <li><em>init:</em> Before the loop executes, the initialization of an iteration variable {@code v} of type {@code V}.
6389      * <li><em>step:</em> When a clause executes, an update step for the iteration variable {@code v}.
6390      * <li><em>pred:</em> When a clause executes, a predicate execution to test for loop exit.
6391      * <li><em>fini:</em> If a clause causes a loop exit, a finalizer execution to compute the loop's return value.
6392      * </ul>
6393      * The full sequence of all iteration variable types, in clause order, will be notated as {@code (V...)}.
6394      * The values themselves will be {@code (v...)}.  When we speak of "parameter lists", we will usually
6395      * be referring to types, but in some contexts (describing execution) the lists will be of actual values.
6396      * <p>
6397      * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in
6398      * this case. See below for a detailed description.
6399      * <p>
6400      * <em>Parameters optional everywhere:</em>
6401      * Each clause function is allowed but not required to accept a parameter for each iteration variable {@code v}.
6402      * As an exception, the init functions cannot take any {@code v} parameters,
6403      * because those values are not yet computed when the init functions are executed.
6404      * Any clause function may neglect to take any trailing subsequence of parameters it is entitled to take.
6405      * In fact, any clause function may take no arguments at all.
6406      * <p>
6407      * <em>Loop parameters:</em>
6408      * A clause function may take all the iteration variable values it is entitled to, in which case
6409      * it may also take more trailing parameters. Such extra values are called <em>loop parameters</em>,
6410      * with their types and values notated as {@code (A...)} and {@code (a...)}.
6411      * These become the parameters of the resulting loop handle, to be supplied whenever the loop is executed.
6412      * (Since init functions do not accept iteration variables {@code v}, any parameter to an
6413      * init function is automatically a loop parameter {@code a}.)
6414      * As with iteration variables, clause functions are allowed but not required to accept loop parameters.
6415      * These loop parameters act as loop-invariant values visible across the whole loop.
6416      * <p>
6417      * <em>Parameters visible everywhere:</em>
6418      * Each non-init clause function is permitted to observe the entire loop state, because it can be passed the full
6419      * list {@code (v... a...)} of current iteration variable values and incoming loop parameters.
6420      * The init functions can observe initial pre-loop state, in the form {@code (a...)}.
6421      * Most clause functions will not need all of this information, but they will be formally connected to it
6422      * as if by {@link #dropArguments}.
6423      * <a id="astar"></a>
6424      * More specifically, we shall use the notation {@code (V*)} to express an arbitrary prefix of a full
6425      * sequence {@code (V...)} (and likewise for {@code (v*)}, {@code (A*)}, {@code (a*)}).
6426      * In that notation, the general form of an init function parameter list
6427      * is {@code (A*)}, and the general form of a non-init function parameter list is {@code (V*)} or {@code (V... A*)}.
6428      * <p>
6429      * <em>Checking clause structure:</em>
6430      * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the
6431      * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must"
6432      * corresponds to a place where {@link IllegalArgumentException} will be thrown if the required constraint is not
6433      * met by the inputs to the loop combinator.
6434      * <p>
6435      * <em>Effectively identical sequences:</em>
6436      * <a id="effid"></a>
6437      * A parameter list {@code A} is defined to be <em>effectively identical</em> to another parameter list {@code B}
6438      * if {@code A} and {@code B} are identical, or if {@code A} is shorter and is identical with a proper prefix of {@code B}.
6439      * When speaking of an unordered set of parameter lists, we say they the set is "effectively identical"
6440      * as a whole if the set contains a longest list, and all members of the set are effectively identical to
6441      * that longest list.
6442      * For example, any set of type sequences of the form {@code (V*)} is effectively identical,
6443      * and the same is true if more sequences of the form {@code (V... A*)} are added.
6444      * <p>
6445      * <em>Step 0: Determine clause structure.</em><ol type="a">
6446      * <li>The clause array (of type {@code MethodHandle[][]}) must be non-{@code null} and contain at least one element.
6447      * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements.
6448      * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length
6449      * four. Padding takes place by appending elements to the array.
6450      * <li>Clauses with all {@code null}s are disregarded.
6451      * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini".
6452      * </ol>
6453      * <p>
6454      * <em>Step 1A: Determine iteration variable types {@code (V...)}.</em><ol type="a">
6455      * <li>The iteration variable type for each clause is determined using the clause's init and step return types.
6456      * <li>If both functions are omitted, there is no iteration variable for the corresponding clause ({@code void} is
6457      * used as the type to indicate that). If one of them is omitted, the other's return type defines the clause's
6458      * iteration variable type. If both are given, the common return type (they must be identical) defines the clause's
6459      * iteration variable type.
6460      * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}.
6461      * <li>This list of types is called the "iteration variable types" ({@code (V...)}).
6462      * </ol>
6463      * <p>
6464      * <em>Step 1B: Determine loop parameters {@code (A...)}.</em><ul>
6465      * <li>Examine and collect init function parameter lists (which are of the form {@code (A*)}).
6466      * <li>Examine and collect the suffixes of the step, pred, and fini parameter lists, after removing the iteration variable types.
6467      * (They must have the form {@code (V... A*)}; collect the {@code (A*)} parts only.)
6468      * <li>Do not collect suffixes from step, pred, and fini parameter lists that do not begin with all the iteration variable types.
6469      * (These types will be checked in step 2, along with all the clause function types.)
6470      * <li>Omitted clause functions are ignored.  (Equivalently, they are deemed to have empty parameter lists.)
6471      * <li>All of the collected parameter lists must be effectively identical.
6472      * <li>The longest parameter list (which is necessarily unique) is called the "external parameter list" ({@code (A...)}).
6473      * <li>If there is no such parameter list, the external parameter list is taken to be the empty sequence.
6474      * <li>The combined list consisting of iteration variable types followed by the external parameter types is called
6475      * the "internal parameter list".
6476      * </ul>
6477      * <p>
6478      * <em>Step 1C: Determine loop return type.</em><ol type="a">
6479      * <li>Examine fini function return types, disregarding omitted fini functions.
6480      * <li>If there are no fini functions, the loop return type is {@code void}.
6481      * <li>Otherwise, the common return type {@code R} of the fini functions (their return types must be identical) defines the loop return
6482      * type.
6483      * </ol>
6484      * <p>
6485      * <em>Step 1D: Check other types.</em><ol type="a">
6486      * <li>There must be at least one non-omitted pred function.
6487      * <li>Every non-omitted pred function must have a {@code boolean} return type.
6488      * </ol>
6489      * <p>
6490      * <em>Step 2: Determine parameter lists.</em><ol type="a">
6491      * <li>The parameter list for the resulting loop handle will be the external parameter list {@code (A...)}.
6492      * <li>The parameter list for init functions will be adjusted to the external parameter list.
6493      * (Note that their parameter lists are already effectively identical to this list.)
6494      * <li>The parameter list for every non-omitted, non-init (step, pred, and fini) function must be
6495      * effectively identical to the internal parameter list {@code (V... A...)}.
6496      * </ol>
6497      * <p>
6498      * <em>Step 3: Fill in omitted functions.</em><ol type="a">
6499      * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
6500      * type.
6501      * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
6502      * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
6503      * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
6504      * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
6505      * as this clause is concerned.  Note that in such cases the corresponding fini function is unreachable.)
6506      * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
6507      * loop return type.
6508      * </ol>
6509      * <p>
6510      * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
6511      * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
6512      * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
6513      * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
6514      * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
6515      * pad out the end of the list.
6516      * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
6517      * </ol>
6518      * <p>
6519      * <em>Final observations.</em><ol type="a">
6520      * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
6521      * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
6522      * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
6523      * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
6524      * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
6525      * <li>Each pair of init and step functions agrees in their return type {@code V}.
6526      * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
6527      * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
6528      * </ol>
6529      * <p>
6530      * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
6531      * <ul>
6532      * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
6533      * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
6534      * (Only one {@code Pn} has to be non-{@code null}.)
6535      * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
6536      * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
6537      * <li>It must be that {@code Vn == Bn} for {@code n = 1..min(X,Q)}.
6538      * <li>The parameter types {@code Vn} will be interpreted as loop-local state elements {@code (V...)}.
6539      * <li>Any remaining types {@code BQ+1..BX} (if {@code Q<X}) will determine
6540      * the resulting loop handle's parameter types {@code (A...)}.
6541      * </ul>
6542      * In this example, the loop handle parameters {@code (A...)} were derived from the step functions,
6543      * which is natural if most of the loop computation happens in the steps.  For some loops,
6544      * the burden of computation might be heaviest in the pred functions, and so the pred functions
6545      * might need to accept the loop parameter values.  For loops with complex exit logic, the fini
6546      * functions might need to accept loop parameters, and likewise for loops with complex entry logic,
6547      * where the init functions will need the extra parameters.  For such reasons, the rules for
6548      * determining these parameters are as symmetric as possible, across all clause parts.
6549      * In general, the loop parameters function as common invariant values across the whole
6550      * loop, while the iteration variables function as common variant values, or (if there is
6551      * no step function) as internal loop invariant temporaries.
6552      * <p>
6553      * <em>Loop execution.</em><ol type="a">
6554      * <li>When the loop is called, the loop input values are saved in locals, to be passed to
6555      * every clause function. These locals are loop invariant.
6556      * <li>Each init function is executed in clause order (passing the external arguments {@code (a...)})
6557      * and the non-{@code void} values are saved (as the iteration variables {@code (v...)}) into locals.
6558      * These locals will be loop varying (unless their steps behave as identity functions, as noted above).
6559      * <li>All function executions (except init functions) will be passed the internal parameter list, consisting of
6560      * the non-{@code void} iteration values {@code (v...)} (in clause order) and then the loop inputs {@code (a...)}
6561      * (in argument order).
6562      * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function
6563      * returns {@code false}.
6564      * <li>The non-{@code void} result from a step function call is used to update the corresponding value in the
6565      * sequence {@code (v...)} of loop variables.
6566      * The updated value is immediately visible to all subsequent function calls.
6567      * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value
6568      * (of type {@code R}) is returned from the loop as a whole.
6569      * <li>If all the pred functions always return true, no fini function is ever invoked, and the loop cannot exit
6570      * except by throwing an exception.
6571      * </ol>
6572      * <p>
6573      * <em>Usage tips.</em>
6574      * <ul>
6575      * <li>Although each step function will receive the current values of <em>all</em> the loop variables,
6576      * sometimes a step function only needs to observe the current value of its own variable.
6577      * In that case, the step function may need to explicitly {@linkplain #dropArguments drop all preceding loop variables}.
6578      * This will require mentioning their types, in an expression like {@code dropArguments(step, 0, V0.class, ...)}.
6579      * <li>Loop variables are not required to vary; they can be loop invariant.  A clause can create
6580      * a loop invariant by a suitable init function with no step, pred, or fini function.  This may be
6581      * useful to "wire" an incoming loop argument into the step or pred function of an adjacent loop variable.
6582      * <li>If some of the clause functions are virtual methods on an instance, the instance
6583      * itself can be conveniently placed in an initial invariant loop "variable", using an initial clause
6584      * like {@code new MethodHandle[]{identity(ObjType.class)}}.  In that case, the instance reference
6585      * will be the first iteration variable value, and it will be easy to use virtual
6586      * methods as clause parts, since all of them will take a leading instance reference matching that value.
6587      * </ul>
6588      * <p>
6589      * Here is pseudocode for the resulting loop handle. As above, {@code V} and {@code v} represent the types
6590      * and values of loop variables; {@code A} and {@code a} represent arguments passed to the whole loop;
6591      * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
6592      * <blockquote><pre>{@code
6593      * V... init...(A...);
6594      * boolean pred...(V..., A...);
6595      * V... step...(V..., A...);
6596      * R fini...(V..., A...);
6597      * R loop(A... a) {
6598      *   V... v... = init...(a...);
6599      *   for (;;) {
6600      *     for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
6601      *       v = s(v..., a...);
6602      *       if (!p(v..., a...)) {
6603      *         return f(v..., a...);
6604      *       }
6605      *     }
6606      *   }
6607      * }
6608      * }</pre></blockquote>
6609      * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
6610      * to their full length, even though individual clause functions may neglect to take them all.
6611      * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
6612      *
6613      * @apiNote Example:
6614      * <blockquote><pre>{@code
6615      * // iterative implementation of the factorial function as a loop handle
6616      * static int one(int k) { return 1; }
6617      * static int inc(int i, int acc, int k) { return i + 1; }
6618      * static int mult(int i, int acc, int k) { return i * acc; }
6619      * static boolean pred(int i, int acc, int k) { return i < k; }
6620      * static int fin(int i, int acc, int k) { return acc; }
6621      * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6622      * // null initializer for counter, should initialize to 0
6623      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6624      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6625      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6626      * assertEquals(120, loop.invoke(5));
6627      * }</pre></blockquote>
6628      * The same example, dropping arguments and using combinators:
6629      * <blockquote><pre>{@code
6630      * // simplified implementation of the factorial function as a loop handle
6631      * static int inc(int i) { return i + 1; } // drop acc, k
6632      * static int mult(int i, int acc) { return i * acc; } //drop k
6633      * static boolean cmp(int i, int k) { return i < k; }
6634      * // assume MH_inc, MH_mult, and MH_cmp are handles to the above methods
6635      * // null initializer for counter, should initialize to 0
6636      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6637      * MethodHandle MH_pred = MethodHandles.dropArguments(MH_cmp, 1, int.class); // drop acc
6638      * MethodHandle MH_fin = MethodHandles.dropArguments(MethodHandles.identity(int.class), 0, int.class); // drop i
6639      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6640      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6641      * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
6642      * assertEquals(720, loop.invoke(6));
6643      * }</pre></blockquote>
6644      * A similar example, using a helper object to hold a loop parameter:
6645      * <blockquote><pre>{@code
6646      * // instance-based implementation of the factorial function as a loop handle
6647      * static class FacLoop {
6648      *   final int k;
6649      *   FacLoop(int k) { this.k = k; }
6650      *   int inc(int i) { return i + 1; }
6651      *   int mult(int i, int acc) { return i * acc; }
6652      *   boolean pred(int i) { return i < k; }
6653      *   int fin(int i, int acc) { return acc; }
6654      * }
6655      * // assume MH_FacLoop is a handle to the constructor
6656      * // assume MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
6657      * // null initializer for counter, should initialize to 0
6658      * MethodHandle MH_one = MethodHandles.constant(int.class, 1);
6659      * MethodHandle[] instanceClause = new MethodHandle[]{MH_FacLoop};
6660      * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
6661      * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
6662      * MethodHandle loop = MethodHandles.loop(instanceClause, counterClause, accumulatorClause);
6663      * assertEquals(5040, loop.invoke(7));
6664      * }</pre></blockquote>
6665      *
6666      * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above.
6667      *
6668      * @return a method handle embodying the looping behavior as defined by the arguments.
6669      *
6670      * @throws IllegalArgumentException in case any of the constraints described above is violated.
6671      *
6672      * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle)
6673      * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6674      * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle)
6675      * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle)
6676      * @since 9
6677      */
6678     public static MethodHandle loop(MethodHandle[]... clauses) {
6679         // Step 0: determine clause structure.
6680         loopChecks0(clauses);
6681 
6682         List<MethodHandle> init = new ArrayList<>();
6683         List<MethodHandle> step = new ArrayList<>();
6684         List<MethodHandle> pred = new ArrayList<>();
6685         List<MethodHandle> fini = new ArrayList<>();
6686 
6687         Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> {
6688             init.add(clause[0]); // all clauses have at least length 1
6689             step.add(clause.length <= 1 ? null : clause[1]);
6690             pred.add(clause.length <= 2 ? null : clause[2]);
6691             fini.add(clause.length <= 3 ? null : clause[3]);
6692         });
6693 
6694         assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1;
6695         final int nclauses = init.size();
6696 
6697         // Step 1A: determine iteration variables (V...).
6698         final List<Class<?>> iterationVariableTypes = new ArrayList<>();
6699         for (int i = 0; i < nclauses; ++i) {
6700             MethodHandle in = init.get(i);
6701             MethodHandle st = step.get(i);
6702             if (in == null && st == null) {
6703                 iterationVariableTypes.add(void.class);
6704             } else if (in != null && st != null) {
6705                 loopChecks1a(i, in, st);
6706                 iterationVariableTypes.add(in.type().returnType());
6707             } else {
6708                 iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType());
6709             }
6710         }
6711         final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class).toList();
6712 
6713         // Step 1B: determine loop parameters (A...).
6714         final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size());
6715         loopChecks1b(init, commonSuffix);
6716 
6717         // Step 1C: determine loop return type.
6718         // Step 1D: check other types.
6719         // local variable required here; see JDK-8223553
6720         Stream<Class<?>> cstream = fini.stream().filter(Objects::nonNull).map(MethodHandle::type)
6721                 .map(MethodType::returnType);
6722         final Class<?> loopReturnType = cstream.findFirst().orElse(void.class);
6723         loopChecks1cd(pred, fini, loopReturnType);
6724 
6725         // Step 2: determine parameter lists.
6726         final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix);
6727         commonParameterSequence.addAll(commonSuffix);
6728         loopChecks2(step, pred, fini, commonParameterSequence);
6729 
6730         // Step 3: fill in omitted functions.
6731         for (int i = 0; i < nclauses; ++i) {
6732             Class<?> t = iterationVariableTypes.get(i);
6733             if (init.get(i) == null) {
6734                 init.set(i, empty(methodType(t, commonSuffix)));
6735             }
6736             if (step.get(i) == null) {
6737                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
6738             }
6739             if (pred.get(i) == null) {
6740                 pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
6741             }
6742             if (fini.get(i) == null) {
6743                 fini.set(i, empty(methodType(t, commonParameterSequence)));
6744             }
6745         }
6746 
6747         // Step 4: fill in missing parameter types.
6748         // Also convert all handles to fixed-arity handles.
6749         List<MethodHandle> finit = fixArities(fillParameterTypes(init, commonSuffix));
6750         List<MethodHandle> fstep = fixArities(fillParameterTypes(step, commonParameterSequence));
6751         List<MethodHandle> fpred = fixArities(fillParameterTypes(pred, commonParameterSequence));
6752         List<MethodHandle> ffini = fixArities(fillParameterTypes(fini, commonParameterSequence));
6753 
6754         assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList).
6755                 allMatch(pl -> pl.equals(commonSuffix));
6756         assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList).
6757                 allMatch(pl -> pl.equals(commonParameterSequence));
6758 
6759         return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini);
6760     }
6761 
6762     private static void loopChecks0(MethodHandle[][] clauses) {
6763         if (clauses == null || clauses.length == 0) {
6764             throw newIllegalArgumentException("null or no clauses passed");
6765         }
6766         if (Stream.of(clauses).anyMatch(Objects::isNull)) {
6767             throw newIllegalArgumentException("null clauses are not allowed");
6768         }
6769         if (Stream.of(clauses).anyMatch(c -> c.length > 4)) {
6770             throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements.");
6771         }
6772     }
6773 
6774     private static void loopChecks1a(int i, MethodHandle in, MethodHandle st) {
6775         if (in.type().returnType() != st.type().returnType()) {
6776             throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(),
6777                     st.type().returnType());
6778         }
6779     }
6780 
6781     private static List<Class<?>> longestParameterList(Stream<MethodHandle> mhs, int skipSize) {
6782         final List<Class<?>> empty = List.of();
6783         final List<Class<?>> longest = mhs.filter(Objects::nonNull).
6784                 // take only those that can contribute to a common suffix because they are longer than the prefix
6785                         map(MethodHandle::type).
6786                         filter(t -> t.parameterCount() > skipSize).
6787                         map(MethodType::parameterList).
6788                         reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6789         return longest.isEmpty() ? empty : longest.subList(skipSize, longest.size());
6790     }
6791 
6792     private static List<Class<?>> longestParameterList(List<List<Class<?>>> lists) {
6793         final List<Class<?>> empty = List.of();
6794         return lists.stream().reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty);
6795     }
6796 
6797     private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) {
6798         final List<Class<?>> longest1 = longestParameterList(Stream.of(step, pred, fini).flatMap(List::stream), cpSize);
6799         final List<Class<?>> longest2 = longestParameterList(init.stream(), 0);
6800         return longestParameterList(Arrays.asList(longest1, longest2));
6801     }
6802 
6803     private static void loopChecks1b(List<MethodHandle> init, List<Class<?>> commonSuffix) {
6804         if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).
6805                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonSuffix))) {
6806             throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init +
6807                     " (common suffix: " + commonSuffix + ")");
6808         }
6809     }
6810 
6811     private static void loopChecks1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) {
6812         if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6813                 anyMatch(t -> t != loopReturnType)) {
6814             throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " +
6815                     loopReturnType + ")");
6816         }
6817 
6818         if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) {
6819             throw newIllegalArgumentException("no predicate found", pred);
6820         }
6821         if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType).
6822                 anyMatch(t -> t != boolean.class)) {
6823             throw newIllegalArgumentException("predicates must have boolean return type", pred);
6824         }
6825     }
6826 
6827     private static void loopChecks2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) {
6828         if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type).
6829                 anyMatch(t -> !t.effectivelyIdenticalParameters(0, commonParameterSequence))) {
6830             throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step +
6831                     "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")");
6832         }
6833     }
6834 
6835     private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) {
6836         return hs.stream().map(h -> {
6837             int pc = h.type().parameterCount();
6838             int tpsize = targetParams.size();
6839             return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
6840         }).toList();
6841     }
6842 
6843     private static List<MethodHandle> fixArities(List<MethodHandle> hs) {
6844         return hs.stream().map(MethodHandle::asFixedArity).toList();
6845     }
6846 
6847     /**
6848      * Constructs a {@code while} loop from an initializer, a body, and a predicate.
6849      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6850      * <p>
6851      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6852      * method will, in each iteration, first evaluate the predicate and then execute its body (if the predicate
6853      * evaluates to {@code true}).
6854      * The loop will terminate once the predicate evaluates to {@code false} (the body will not be executed in this case).
6855      * <p>
6856      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6857      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6858      * and updated with the value returned from its invocation. The result of loop execution will be
6859      * the final value of the additional loop-local variable (if present).
6860      * <p>
6861      * The following rules hold for these argument handles:<ul>
6862      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6863      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6864      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6865      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6866      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6867      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6868      * It will constrain the parameter lists of the other loop parts.
6869      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6870      * list {@code (A...)} is called the <em>external parameter list</em>.
6871      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6872      * additional state variable of the loop.
6873      * The body must both accept and return a value of this type {@code V}.
6874      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6875      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6876      * <a href="MethodHandles.html#effid">effectively identical</a>
6877      * to the external parameter list {@code (A...)}.
6878      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6879      * {@linkplain #empty default value}.
6880      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6881      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6882      * effectively identical to the internal parameter list.
6883      * </ul>
6884      * <p>
6885      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6886      * <li>The loop handle's result type is the result type {@code V} of the body.
6887      * <li>The loop handle's parameter types are the types {@code (A...)},
6888      * from the external parameter list.
6889      * </ul>
6890      * <p>
6891      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
6892      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
6893      * passed to the loop.
6894      * <blockquote><pre>{@code
6895      * V init(A...);
6896      * boolean pred(V, A...);
6897      * V body(V, A...);
6898      * V whileLoop(A... a...) {
6899      *   V v = init(a...);
6900      *   while (pred(v, a...)) {
6901      *     v = body(v, a...);
6902      *   }
6903      *   return v;
6904      * }
6905      * }</pre></blockquote>
6906      *
6907      * @apiNote Example:
6908      * <blockquote><pre>{@code
6909      * // implement the zip function for lists as a loop handle
6910      * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); }
6911      * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); }
6912      * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) {
6913      *   zip.add(a.next());
6914      *   zip.add(b.next());
6915      *   return zip;
6916      * }
6917      * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods
6918      * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep);
6919      * List<String> a = Arrays.asList("a", "b", "c", "d");
6920      * List<String> b = Arrays.asList("e", "f", "g", "h");
6921      * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h");
6922      * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator()));
6923      * }</pre></blockquote>
6924      *
6925      *
6926      * @apiNote The implementation of this method can be expressed as follows:
6927      * <blockquote><pre>{@code
6928      * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6929      *     MethodHandle fini = (body.type().returnType() == void.class
6930      *                         ? null : identity(body.type().returnType()));
6931      *     MethodHandle[]
6932      *         checkExit = { null, null, pred, fini },
6933      *         varBody   = { init, body };
6934      *     return loop(checkExit, varBody);
6935      * }
6936      * }</pre></blockquote>
6937      *
6938      * @param init optional initializer, providing the initial value of the loop variable.
6939      *             May be {@code null}, implying a default initial value.  See above for other constraints.
6940      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
6941      *             above for other constraints.
6942      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
6943      *             See above for other constraints.
6944      *
6945      * @return a method handle implementing the {@code while} loop as described by the arguments.
6946      * @throws IllegalArgumentException if the rules for the arguments are violated.
6947      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
6948      *
6949      * @see #loop(MethodHandle[][])
6950      * @see #doWhileLoop(MethodHandle, MethodHandle, MethodHandle)
6951      * @since 9
6952      */
6953     public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) {
6954         whileLoopChecks(init, pred, body);
6955         MethodHandle fini = identityOrVoid(body.type().returnType());
6956         MethodHandle[] checkExit = { null, null, pred, fini };
6957         MethodHandle[] varBody = { init, body };
6958         return loop(checkExit, varBody);
6959     }
6960 
6961     /**
6962      * Constructs a {@code do-while} loop from an initializer, a body, and a predicate.
6963      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
6964      * <p>
6965      * The {@code pred} handle describes the loop condition; and {@code body}, its body. The loop resulting from this
6966      * method will, in each iteration, first execute its body and then evaluate the predicate.
6967      * The loop will terminate once the predicate evaluates to {@code false} after an execution of the body.
6968      * <p>
6969      * The {@code init} handle describes the initial value of an additional optional loop-local variable.
6970      * In each iteration, this loop-local variable, if present, will be passed to the {@code body}
6971      * and updated with the value returned from its invocation. The result of loop execution will be
6972      * the final value of the additional loop-local variable (if present).
6973      * <p>
6974      * The following rules hold for these argument handles:<ul>
6975      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
6976      * {@code (V A...)V}, where {@code V} is non-{@code void}, or else {@code (A...)void}.
6977      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
6978      * and we will write {@code (V A...)V} with the understanding that a {@code void} type {@code V}
6979      * is quietly dropped from the parameter list, leaving {@code (A...)V}.)
6980      * <li>The parameter list {@code (V A...)} of the body is called the <em>internal parameter list</em>.
6981      * It will constrain the parameter lists of the other loop parts.
6982      * <li>If the iteration variable type {@code V} is dropped from the internal parameter list, the resulting shorter
6983      * list {@code (A...)} is called the <em>external parameter list</em>.
6984      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
6985      * additional state variable of the loop.
6986      * The body must both accept and return a value of this type {@code V}.
6987      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
6988      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
6989      * <a href="MethodHandles.html#effid">effectively identical</a>
6990      * to the external parameter list {@code (A...)}.
6991      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
6992      * {@linkplain #empty default value}.
6993      * <li>The {@code pred} handle must not be {@code null}.  It must have {@code boolean} as its return type.
6994      * Its parameter list (either empty or of the form {@code (V A*)}) must be
6995      * effectively identical to the internal parameter list.
6996      * </ul>
6997      * <p>
6998      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
6999      * <li>The loop handle's result type is the result type {@code V} of the body.
7000      * <li>The loop handle's parameter types are the types {@code (A...)},
7001      * from the external parameter list.
7002      * </ul>
7003      * <p>
7004      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7005      * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument
7006      * passed to the loop.
7007      * <blockquote><pre>{@code
7008      * V init(A...);
7009      * boolean pred(V, A...);
7010      * V body(V, A...);
7011      * V doWhileLoop(A... a...) {
7012      *   V v = init(a...);
7013      *   do {
7014      *     v = body(v, a...);
7015      *   } while (pred(v, a...));
7016      *   return v;
7017      * }
7018      * }</pre></blockquote>
7019      *
7020      * @apiNote Example:
7021      * <blockquote><pre>{@code
7022      * // int i = 0; while (i < limit) { ++i; } return i; => limit
7023      * static int zero(int limit) { return 0; }
7024      * static int step(int i, int limit) { return i + 1; }
7025      * static boolean pred(int i, int limit) { return i < limit; }
7026      * // assume MH_zero, MH_step, and MH_pred are handles to the above methods
7027      * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred);
7028      * assertEquals(23, loop.invoke(23));
7029      * }</pre></blockquote>
7030      *
7031      *
7032      * @apiNote The implementation of this method can be expressed as follows:
7033      * <blockquote><pre>{@code
7034      * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7035      *     MethodHandle fini = (body.type().returnType() == void.class
7036      *                         ? null : identity(body.type().returnType()));
7037      *     MethodHandle[] clause = { init, body, pred, fini };
7038      *     return loop(clause);
7039      * }
7040      * }</pre></blockquote>
7041      *
7042      * @param init optional initializer, providing the initial value of the loop variable.
7043      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7044      * @param body body of the loop, which may not be {@code null}. It controls the loop parameters and result type.
7045      *             See above for other constraints.
7046      * @param pred condition for the loop, which may not be {@code null}. Its result type must be {@code boolean}. See
7047      *             above for other constraints.
7048      *
7049      * @return a method handle implementing the {@code while} loop as described by the arguments.
7050      * @throws IllegalArgumentException if the rules for the arguments are violated.
7051      * @throws NullPointerException if {@code pred} or {@code body} are {@code null}.
7052      *
7053      * @see #loop(MethodHandle[][])
7054      * @see #whileLoop(MethodHandle, MethodHandle, MethodHandle)
7055      * @since 9
7056      */
7057     public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) {
7058         whileLoopChecks(init, pred, body);
7059         MethodHandle fini = identityOrVoid(body.type().returnType());
7060         MethodHandle[] clause = {init, body, pred, fini };
7061         return loop(clause);
7062     }
7063 
7064     private static void whileLoopChecks(MethodHandle init, MethodHandle pred, MethodHandle body) {
7065         Objects.requireNonNull(pred);
7066         Objects.requireNonNull(body);
7067         MethodType bodyType = body.type();
7068         Class<?> returnType = bodyType.returnType();
7069         List<Class<?>> innerList = bodyType.parameterList();
7070         List<Class<?>> outerList = innerList;
7071         if (returnType == void.class) {
7072             // OK
7073         } else if (innerList.isEmpty() || innerList.get(0) != returnType) {
7074             // leading V argument missing => error
7075             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7076             throw misMatchedTypes("body function", bodyType, expected);
7077         } else {
7078             outerList = innerList.subList(1, innerList.size());
7079         }
7080         MethodType predType = pred.type();
7081         if (predType.returnType() != boolean.class ||
7082                 !predType.effectivelyIdenticalParameters(0, innerList)) {
7083             throw misMatchedTypes("loop predicate", predType, methodType(boolean.class, innerList));
7084         }
7085         if (init != null) {
7086             MethodType initType = init.type();
7087             if (initType.returnType() != returnType ||
7088                     !initType.effectivelyIdenticalParameters(0, outerList)) {
7089                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7090             }
7091         }
7092     }
7093 
7094     /**
7095      * Constructs a loop that runs a given number of iterations.
7096      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7097      * <p>
7098      * The number of iterations is determined by the {@code iterations} handle evaluation result.
7099      * The loop counter {@code i} is an extra loop iteration variable of type {@code int}.
7100      * It will be initialized to 0 and incremented by 1 in each iteration.
7101      * <p>
7102      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7103      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7104      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7105      * <p>
7106      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7107      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7108      * iteration variable.
7109      * The result of the loop handle execution will be the final {@code V} value of that variable
7110      * (or {@code void} if there is no {@code V} variable).
7111      * <p>
7112      * The following rules hold for the argument handles:<ul>
7113      * <li>The {@code iterations} handle must not be {@code null}, and must return
7114      * the type {@code int}, referred to here as {@code I} in parameter type lists.
7115      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7116      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7117      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7118      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7119      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7120      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7121      * of types called the <em>internal parameter list</em>.
7122      * It will constrain the parameter lists of the other loop parts.
7123      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7124      * with no additional {@code A} types, then the internal parameter list is extended by
7125      * the argument types {@code A...} of the {@code iterations} handle.
7126      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7127      * list {@code (A...)} is called the <em>external parameter list</em>.
7128      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7129      * additional state variable of the loop.
7130      * The body must both accept a leading parameter and return a value of this type {@code V}.
7131      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7132      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7133      * <a href="MethodHandles.html#effid">effectively identical</a>
7134      * to the external parameter list {@code (A...)}.
7135      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7136      * {@linkplain #empty default value}.
7137      * <li>The parameter list of {@code iterations} (of some form {@code (A*)}) must be
7138      * effectively identical to the external parameter list {@code (A...)}.
7139      * </ul>
7140      * <p>
7141      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7142      * <li>The loop handle's result type is the result type {@code V} of the body.
7143      * <li>The loop handle's parameter types are the types {@code (A...)},
7144      * from the external parameter list.
7145      * </ul>
7146      * <p>
7147      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7148      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7149      * arguments passed to the loop.
7150      * <blockquote><pre>{@code
7151      * int iterations(A...);
7152      * V init(A...);
7153      * V body(V, int, A...);
7154      * V countedLoop(A... a...) {
7155      *   int end = iterations(a...);
7156      *   V v = init(a...);
7157      *   for (int i = 0; i < end; ++i) {
7158      *     v = body(v, i, a...);
7159      *   }
7160      *   return v;
7161      * }
7162      * }</pre></blockquote>
7163      *
7164      * @apiNote Example with a fully conformant body method:
7165      * <blockquote><pre>{@code
7166      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7167      * // => a variation on a well known theme
7168      * static String step(String v, int counter, String init) { return "na " + v; }
7169      * // assume MH_step is a handle to the method above
7170      * MethodHandle fit13 = MethodHandles.constant(int.class, 13);
7171      * MethodHandle start = MethodHandles.identity(String.class);
7172      * MethodHandle loop = MethodHandles.countedLoop(fit13, start, MH_step);
7173      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!"));
7174      * }</pre></blockquote>
7175      *
7176      * @apiNote Example with the simplest possible body method type,
7177      * and passing the number of iterations to the loop invocation:
7178      * <blockquote><pre>{@code
7179      * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s;
7180      * // => a variation on a well known theme
7181      * static String step(String v, int counter ) { return "na " + v; }
7182      * // assume MH_step is a handle to the method above
7183      * MethodHandle count = MethodHandles.dropArguments(MethodHandles.identity(int.class), 1, String.class);
7184      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class);
7185      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i) -> "na " + v
7186      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "Lambdaman!"));
7187      * }</pre></blockquote>
7188      *
7189      * @apiNote Example that treats the number of iterations, string to append to, and string to append
7190      * as loop parameters:
7191      * <blockquote><pre>{@code
7192      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7193      * // => a variation on a well known theme
7194      * static String step(String v, int counter, int iterations_, String pre, String start_) { return pre + " " + v; }
7195      * // assume MH_step is a handle to the method above
7196      * MethodHandle count = MethodHandles.identity(int.class);
7197      * MethodHandle start = MethodHandles.dropArguments(MethodHandles.identity(String.class), 0, int.class, String.class);
7198      * MethodHandle loop = MethodHandles.countedLoop(count, start, MH_step);  // (v, i, _, pre, _) -> pre + " " + v
7199      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke(13, "na", "Lambdaman!"));
7200      * }</pre></blockquote>
7201      *
7202      * @apiNote Example that illustrates the usage of {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}
7203      * to enforce a loop type:
7204      * <blockquote><pre>{@code
7205      * // String s = "Lambdaman!", t = "na"; for (int i = 0; i < 13; ++i) { s = t + " " + s; } return s;
7206      * // => a variation on a well known theme
7207      * static String step(String v, int counter, String pre) { return pre + " " + v; }
7208      * // assume MH_step is a handle to the method above
7209      * MethodType loopType = methodType(String.class, String.class, int.class, String.class);
7210      * MethodHandle count = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(int.class),    0, loopType.parameterList(), 1);
7211      * MethodHandle start = MethodHandles.dropArgumentsToMatch(MethodHandles.identity(String.class), 0, loopType.parameterList(), 2);
7212      * MethodHandle body  = MethodHandles.dropArgumentsToMatch(MH_step,                              2, loopType.parameterList(), 0);
7213      * MethodHandle loop = MethodHandles.countedLoop(count, start, body);  // (v, i, pre, _, _) -> pre + " " + v
7214      * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("na", 13, "Lambdaman!"));
7215      * }</pre></blockquote>
7216      *
7217      * @apiNote The implementation of this method can be expressed as follows:
7218      * <blockquote><pre>{@code
7219      * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7220      *     return countedLoop(empty(iterations.type()), iterations, init, body);
7221      * }
7222      * }</pre></blockquote>
7223      *
7224      * @param iterations a non-{@code null} handle to return the number of iterations this loop should run. The handle's
7225      *                   result type must be {@code int}. See above for other constraints.
7226      * @param init optional initializer, providing the initial value of the loop variable.
7227      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7228      * @param body body of the loop, which may not be {@code null}.
7229      *             It controls the loop parameters and result type in the standard case (see above for details).
7230      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7231      *             and may accept any number of additional types.
7232      *             See above for other constraints.
7233      *
7234      * @return a method handle representing the loop.
7235      * @throws NullPointerException if either of the {@code iterations} or {@code body} handles is {@code null}.
7236      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7237      *
7238      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle, MethodHandle)
7239      * @since 9
7240      */
7241     public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) {
7242         return countedLoop(empty(iterations.type()), iterations, init, body);
7243     }
7244 
7245     /**
7246      * Constructs a loop that counts over a range of numbers.
7247      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7248      * <p>
7249      * The loop counter {@code i} is a loop iteration variable of type {@code int}.
7250      * The {@code start} and {@code end} handles determine the start (inclusive) and end (exclusive)
7251      * values of the loop counter.
7252      * The loop counter will be initialized to the {@code int} value returned from the evaluation of the
7253      * {@code start} handle and run to the value returned from {@code end} (exclusively) with a step width of 1.
7254      * <p>
7255      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7256      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7257      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7258      * <p>
7259      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7260      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7261      * iteration variable.
7262      * The result of the loop handle execution will be the final {@code V} value of that variable
7263      * (or {@code void} if there is no {@code V} variable).
7264      * <p>
7265      * The following rules hold for the argument handles:<ul>
7266      * <li>The {@code start} and {@code end} handles must not be {@code null}, and must both return
7267      * the common type {@code int}, referred to here as {@code I} in parameter type lists.
7268      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7269      * {@code (V I A...)V}, where {@code V} is non-{@code void}, or else {@code (I A...)void}.
7270      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7271      * and we will write {@code (V I A...)V} with the understanding that a {@code void} type {@code V}
7272      * is quietly dropped from the parameter list, leaving {@code (I A...)V}.)
7273      * <li>The parameter list {@code (V I A...)} of the body contributes to a list
7274      * of types called the <em>internal parameter list</em>.
7275      * It will constrain the parameter lists of the other loop parts.
7276      * <li>As a special case, if the body contributes only {@code V} and {@code I} types,
7277      * with no additional {@code A} types, then the internal parameter list is extended by
7278      * the argument types {@code A...} of the {@code end} handle.
7279      * <li>If the iteration variable types {@code (V I)} are dropped from the internal parameter list, the resulting shorter
7280      * list {@code (A...)} is called the <em>external parameter list</em>.
7281      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7282      * additional state variable of the loop.
7283      * The body must both accept a leading parameter and return a value of this type {@code V}.
7284      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7285      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7286      * <a href="MethodHandles.html#effid">effectively identical</a>
7287      * to the external parameter list {@code (A...)}.
7288      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7289      * {@linkplain #empty default value}.
7290      * <li>The parameter list of {@code start} (of some form {@code (A*)}) must be
7291      * effectively identical to the external parameter list {@code (A...)}.
7292      * <li>Likewise, the parameter list of {@code end} must be effectively identical
7293      * to the external parameter list.
7294      * </ul>
7295      * <p>
7296      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7297      * <li>The loop handle's result type is the result type {@code V} of the body.
7298      * <li>The loop handle's parameter types are the types {@code (A...)},
7299      * from the external parameter list.
7300      * </ul>
7301      * <p>
7302      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7303      * the second loop variable as well as the result type of the loop; and {@code A...}/{@code a...} represent
7304      * arguments passed to the loop.
7305      * <blockquote><pre>{@code
7306      * int start(A...);
7307      * int end(A...);
7308      * V init(A...);
7309      * V body(V, int, A...);
7310      * V countedLoop(A... a...) {
7311      *   int e = end(a...);
7312      *   int s = start(a...);
7313      *   V v = init(a...);
7314      *   for (int i = s; i < e; ++i) {
7315      *     v = body(v, i, a...);
7316      *   }
7317      *   return v;
7318      * }
7319      * }</pre></blockquote>
7320      *
7321      * @apiNote The implementation of this method can be expressed as follows:
7322      * <blockquote><pre>{@code
7323      * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7324      *     MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class);
7325      *     // assume MH_increment and MH_predicate are handles to implementation-internal methods with
7326      *     // the following semantics:
7327      *     // MH_increment: (int limit, int counter) -> counter + 1
7328      *     // MH_predicate: (int limit, int counter) -> counter < limit
7329      *     Class<?> counterType = start.type().returnType();  // int
7330      *     Class<?> returnType = body.type().returnType();
7331      *     MethodHandle incr = MH_increment, pred = MH_predicate, retv = null;
7332      *     if (returnType != void.class) {  // ignore the V variable
7333      *         incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7334      *         pred = dropArguments(pred, 1, returnType);  // ditto
7335      *         retv = dropArguments(identity(returnType), 0, counterType); // ignore limit
7336      *     }
7337      *     body = dropArguments(body, 0, counterType);  // ignore the limit variable
7338      *     MethodHandle[]
7339      *         loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7340      *         bodyClause = { init, body },            // v = init(); v = body(v, i)
7341      *         indexVar   = { start, incr };           // i = start(); i = i + 1
7342      *     return loop(loopLimit, bodyClause, indexVar);
7343      * }
7344      * }</pre></blockquote>
7345      *
7346      * @param start a non-{@code null} handle to return the start value of the loop counter, which must be {@code int}.
7347      *              See above for other constraints.
7348      * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to
7349      *            {@code end-1}). The result type must be {@code int}. See above for other constraints.
7350      * @param init optional initializer, providing the initial value of the loop variable.
7351      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7352      * @param body body of the loop, which may not be {@code null}.
7353      *             It controls the loop parameters and result type in the standard case (see above for details).
7354      *             It must accept its own return type (if non-void) plus an {@code int} parameter (for the counter),
7355      *             and may accept any number of additional types.
7356      *             See above for other constraints.
7357      *
7358      * @return a method handle representing the loop.
7359      * @throws NullPointerException if any of the {@code start}, {@code end}, or {@code body} handles is {@code null}.
7360      * @throws IllegalArgumentException if any argument violates the rules formulated above.
7361      *
7362      * @see #countedLoop(MethodHandle, MethodHandle, MethodHandle)
7363      * @since 9
7364      */
7365     public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7366         countedLoopChecks(start, end, init, body);
7367         Class<?> counterType = start.type().returnType();  // int, but who's counting?
7368         Class<?> limitType   = end.type().returnType();    // yes, int again
7369         Class<?> returnType  = body.type().returnType();
7370         MethodHandle incr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep);
7371         MethodHandle pred = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred);
7372         MethodHandle retv = null;
7373         if (returnType != void.class) {
7374             incr = dropArguments(incr, 1, returnType);  // (limit, v, i) => (limit, i)
7375             pred = dropArguments(pred, 1, returnType);  // ditto
7376             retv = dropArguments(identity(returnType), 0, counterType);
7377         }
7378         body = dropArguments(body, 0, counterType);  // ignore the limit variable
7379         MethodHandle[]
7380             loopLimit  = { end, null, pred, retv }, // limit = end(); i < limit || return v
7381             bodyClause = { init, body },            // v = init(); v = body(v, i)
7382             indexVar   = { start, incr };           // i = start(); i = i + 1
7383         return loop(loopLimit, bodyClause, indexVar);
7384     }
7385 
7386     private static void countedLoopChecks(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) {
7387         Objects.requireNonNull(start);
7388         Objects.requireNonNull(end);
7389         Objects.requireNonNull(body);
7390         Class<?> counterType = start.type().returnType();
7391         if (counterType != int.class) {
7392             MethodType expected = start.type().changeReturnType(int.class);
7393             throw misMatchedTypes("start function", start.type(), expected);
7394         } else if (end.type().returnType() != counterType) {
7395             MethodType expected = end.type().changeReturnType(counterType);
7396             throw misMatchedTypes("end function", end.type(), expected);
7397         }
7398         MethodType bodyType = body.type();
7399         Class<?> returnType = bodyType.returnType();
7400         List<Class<?>> innerList = bodyType.parameterList();
7401         // strip leading V value if present
7402         int vsize = (returnType == void.class ? 0 : 1);
7403         if (vsize != 0 && (innerList.isEmpty() || innerList.get(0) != returnType)) {
7404             // argument list has no "V" => error
7405             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7406             throw misMatchedTypes("body function", bodyType, expected);
7407         } else if (innerList.size() <= vsize || innerList.get(vsize) != counterType) {
7408             // missing I type => error
7409             MethodType expected = bodyType.insertParameterTypes(vsize, counterType);
7410             throw misMatchedTypes("body function", bodyType, expected);
7411         }
7412         List<Class<?>> outerList = innerList.subList(vsize + 1, innerList.size());
7413         if (outerList.isEmpty()) {
7414             // special case; take lists from end handle
7415             outerList = end.type().parameterList();
7416             innerList = bodyType.insertParameterTypes(vsize + 1, outerList).parameterList();
7417         }
7418         MethodType expected = methodType(counterType, outerList);
7419         if (!start.type().effectivelyIdenticalParameters(0, outerList)) {
7420             throw misMatchedTypes("start parameter types", start.type(), expected);
7421         }
7422         if (end.type() != start.type() &&
7423             !end.type().effectivelyIdenticalParameters(0, outerList)) {
7424             throw misMatchedTypes("end parameter types", end.type(), expected);
7425         }
7426         if (init != null) {
7427             MethodType initType = init.type();
7428             if (initType.returnType() != returnType ||
7429                 !initType.effectivelyIdenticalParameters(0, outerList)) {
7430                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, outerList));
7431             }
7432         }
7433     }
7434 
7435     /**
7436      * Constructs a loop that ranges over the values produced by an {@code Iterator<T>}.
7437      * This is a convenience wrapper for the {@linkplain #loop(MethodHandle[][]) generic loop combinator}.
7438      * <p>
7439      * The iterator itself will be determined by the evaluation of the {@code iterator} handle.
7440      * Each value it produces will be stored in a loop iteration variable of type {@code T}.
7441      * <p>
7442      * If the {@code body} handle returns a non-{@code void} type {@code V}, a leading loop iteration variable
7443      * of that type is also present.  This variable is initialized using the optional {@code init} handle,
7444      * or to the {@linkplain #empty default value} of type {@code V} if that handle is {@code null}.
7445      * <p>
7446      * In each iteration, the iteration variables are passed to an invocation of the {@code body} handle.
7447      * A non-{@code void} value returned from the body (of type {@code V}) updates the leading
7448      * iteration variable.
7449      * The result of the loop handle execution will be the final {@code V} value of that variable
7450      * (or {@code void} if there is no {@code V} variable).
7451      * <p>
7452      * The following rules hold for the argument handles:<ul>
7453      * <li>The {@code body} handle must not be {@code null}; its type must be of the form
7454      * {@code (V T A...)V}, where {@code V} is non-{@code void}, or else {@code (T A...)void}.
7455      * (In the {@code void} case, we assign the type {@code void} to the name {@code V},
7456      * and we will write {@code (V T A...)V} with the understanding that a {@code void} type {@code V}
7457      * is quietly dropped from the parameter list, leaving {@code (T A...)V}.)
7458      * <li>The parameter list {@code (V T A...)} of the body contributes to a list
7459      * of types called the <em>internal parameter list</em>.
7460      * It will constrain the parameter lists of the other loop parts.
7461      * <li>As a special case, if the body contributes only {@code V} and {@code T} types,
7462      * with no additional {@code A} types, then the internal parameter list is extended by
7463      * the argument types {@code A...} of the {@code iterator} handle; if it is {@code null} the
7464      * single type {@code Iterable} is added and constitutes the {@code A...} list.
7465      * <li>If the iteration variable types {@code (V T)} are dropped from the internal parameter list, the resulting shorter
7466      * list {@code (A...)} is called the <em>external parameter list</em>.
7467      * <li>The body return type {@code V}, if non-{@code void}, determines the type of an
7468      * additional state variable of the loop.
7469      * The body must both accept a leading parameter and return a value of this type {@code V}.
7470      * <li>If {@code init} is non-{@code null}, it must have return type {@code V}.
7471      * Its parameter list (of some <a href="MethodHandles.html#astar">form {@code (A*)}</a>) must be
7472      * <a href="MethodHandles.html#effid">effectively identical</a>
7473      * to the external parameter list {@code (A...)}.
7474      * <li>If {@code init} is {@code null}, the loop variable will be initialized to its
7475      * {@linkplain #empty default value}.
7476      * <li>If the {@code iterator} handle is non-{@code null}, it must have the return
7477      * type {@code java.util.Iterator} or a subtype thereof.
7478      * The iterator it produces when the loop is executed will be assumed
7479      * to yield values which can be converted to type {@code T}.
7480      * <li>The parameter list of an {@code iterator} that is non-{@code null} (of some form {@code (A*)}) must be
7481      * effectively identical to the external parameter list {@code (A...)}.
7482      * <li>If {@code iterator} is {@code null} it defaults to a method handle which behaves
7483      * like {@link java.lang.Iterable#iterator()}.  In that case, the internal parameter list
7484      * {@code (V T A...)} must have at least one {@code A} type, and the default iterator
7485      * handle parameter is adjusted to accept the leading {@code A} type, as if by
7486      * the {@link MethodHandle#asType asType} conversion method.
7487      * The leading {@code A} type must be {@code Iterable} or a subtype thereof.
7488      * This conversion step, done at loop construction time, must not throw a {@code WrongMethodTypeException}.
7489      * </ul>
7490      * <p>
7491      * The type {@code T} may be either a primitive or reference.
7492      * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type {@code Iterator},
7493      * the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} to {@code Object}
7494      * as if by the {@link MethodHandle#asType asType} conversion method.
7495      * Therefore, if an iterator of the wrong type appears as the loop is executed, runtime exceptions may occur
7496      * as the result of dynamic conversions performed by {@link MethodHandle#asType(MethodType)}.
7497      * <p>
7498      * The resulting loop handle's result type and parameter signature are determined as follows:<ul>
7499      * <li>The loop handle's result type is the result type {@code V} of the body.
7500      * <li>The loop handle's parameter types are the types {@code (A...)},
7501      * from the external parameter list.
7502      * </ul>
7503      * <p>
7504      * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of
7505      * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the
7506      * structure the loop iterates over, and {@code A...}/{@code a...} represent arguments passed to the loop.
7507      * <blockquote><pre>{@code
7508      * Iterator<T> iterator(A...);  // defaults to Iterable::iterator
7509      * V init(A...);
7510      * V body(V,T,A...);
7511      * V iteratedLoop(A... a...) {
7512      *   Iterator<T> it = iterator(a...);
7513      *   V v = init(a...);
7514      *   while (it.hasNext()) {
7515      *     T t = it.next();
7516      *     v = body(v, t, a...);
7517      *   }
7518      *   return v;
7519      * }
7520      * }</pre></blockquote>
7521      *
7522      * @apiNote Example:
7523      * <blockquote><pre>{@code
7524      * // get an iterator from a list
7525      * static List<String> reverseStep(List<String> r, String e) {
7526      *   r.add(0, e);
7527      *   return r;
7528      * }
7529      * static List<String> newArrayList() { return new ArrayList<>(); }
7530      * // assume MH_reverseStep and MH_newArrayList are handles to the above methods
7531      * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep);
7532      * List<String> list = Arrays.asList("a", "b", "c", "d", "e");
7533      * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a");
7534      * assertEquals(reversedList, (List<String>) loop.invoke(list));
7535      * }</pre></blockquote>
7536      *
7537      * @apiNote The implementation of this method can be expressed approximately as follows:
7538      * <blockquote><pre>{@code
7539      * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7540      *     // assume MH_next, MH_hasNext, MH_startIter are handles to methods of Iterator/Iterable
7541      *     Class<?> returnType = body.type().returnType();
7542      *     Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7543      *     MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype));
7544      *     MethodHandle retv = null, step = body, startIter = iterator;
7545      *     if (returnType != void.class) {
7546      *         // the simple thing first:  in (I V A...), drop the I to get V
7547      *         retv = dropArguments(identity(returnType), 0, Iterator.class);
7548      *         // body type signature (V T A...), internal loop types (I V A...)
7549      *         step = swapArguments(body, 0, 1);  // swap V <-> T
7550      *     }
7551      *     if (startIter == null)  startIter = MH_getIter;
7552      *     MethodHandle[]
7553      *         iterVar    = { startIter, null, MH_hasNext, retv }, // it = iterator; while (it.hasNext())
7554      *         bodyClause = { init, filterArguments(step, 0, nextVal) };  // v = body(v, t, a)
7555      *     return loop(iterVar, bodyClause);
7556      * }
7557      * }</pre></blockquote>
7558      *
7559      * @param iterator an optional handle to return the iterator to start the loop.
7560      *                 If non-{@code null}, the handle must return {@link java.util.Iterator} or a subtype.
7561      *                 See above for other constraints.
7562      * @param init optional initializer, providing the initial value of the loop variable.
7563      *             May be {@code null}, implying a default initial value.  See above for other constraints.
7564      * @param body body of the loop, which may not be {@code null}.
7565      *             It controls the loop parameters and result type in the standard case (see above for details).
7566      *             It must accept its own return type (if non-void) plus a {@code T} parameter (for the iterated values),
7567      *             and may accept any number of additional types.
7568      *             See above for other constraints.
7569      *
7570      * @return a method handle embodying the iteration loop functionality.
7571      * @throws NullPointerException if the {@code body} handle is {@code null}.
7572      * @throws IllegalArgumentException if any argument violates the above requirements.
7573      *
7574      * @since 9
7575      */
7576     public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7577         Class<?> iterableType = iteratedLoopChecks(iterator, init, body);
7578         Class<?> returnType = body.type().returnType();
7579         MethodHandle hasNext = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred);
7580         MethodHandle nextRaw = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext);
7581         MethodHandle startIter;
7582         MethodHandle nextVal;
7583         {
7584             MethodType iteratorType;
7585             if (iterator == null) {
7586                 // derive argument type from body, if available, else use Iterable
7587                 startIter = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator);
7588                 iteratorType = startIter.type().changeParameterType(0, iterableType);
7589             } else {
7590                 // force return type to the internal iterator class
7591                 iteratorType = iterator.type().changeReturnType(Iterator.class);
7592                 startIter = iterator;
7593             }
7594             Class<?> ttype = body.type().parameterType(returnType == void.class ? 0 : 1);
7595             MethodType nextValType = nextRaw.type().changeReturnType(ttype);
7596 
7597             // perform the asType transforms under an exception transformer, as per spec.:
7598             try {
7599                 startIter = startIter.asType(iteratorType);
7600                 nextVal = nextRaw.asType(nextValType);
7601             } catch (WrongMethodTypeException ex) {
7602                 throw new IllegalArgumentException(ex);
7603             }
7604         }
7605 
7606         MethodHandle retv = null, step = body;
7607         if (returnType != void.class) {
7608             // the simple thing first:  in (I V A...), drop the I to get V
7609             retv = dropArguments(identity(returnType), 0, Iterator.class);
7610             // body type signature (V T A...), internal loop types (I V A...)
7611             step = swapArguments(body, 0, 1);  // swap V <-> T
7612         }
7613 
7614         MethodHandle[]
7615             iterVar    = { startIter, null, hasNext, retv },
7616             bodyClause = { init, filterArgument(step, 0, nextVal) };
7617         return loop(iterVar, bodyClause);
7618     }
7619 
7620     private static Class<?> iteratedLoopChecks(MethodHandle iterator, MethodHandle init, MethodHandle body) {
7621         Objects.requireNonNull(body);
7622         MethodType bodyType = body.type();
7623         Class<?> returnType = bodyType.returnType();
7624         List<Class<?>> internalParamList = bodyType.parameterList();
7625         // strip leading V value if present
7626         int vsize = (returnType == void.class ? 0 : 1);
7627         if (vsize != 0 && (internalParamList.isEmpty() || internalParamList.get(0) != returnType)) {
7628             // argument list has no "V" => error
7629             MethodType expected = bodyType.insertParameterTypes(0, returnType);
7630             throw misMatchedTypes("body function", bodyType, expected);
7631         } else if (internalParamList.size() <= vsize) {
7632             // missing T type => error
7633             MethodType expected = bodyType.insertParameterTypes(vsize, Object.class);
7634             throw misMatchedTypes("body function", bodyType, expected);
7635         }
7636         List<Class<?>> externalParamList = internalParamList.subList(vsize + 1, internalParamList.size());
7637         Class<?> iterableType = null;
7638         if (iterator != null) {
7639             // special case; if the body handle only declares V and T then
7640             // the external parameter list is obtained from iterator handle
7641             if (externalParamList.isEmpty()) {
7642                 externalParamList = iterator.type().parameterList();
7643             }
7644             MethodType itype = iterator.type();
7645             if (!Iterator.class.isAssignableFrom(itype.returnType())) {
7646                 throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type");
7647             }
7648             if (!itype.effectivelyIdenticalParameters(0, externalParamList)) {
7649                 MethodType expected = methodType(itype.returnType(), externalParamList);
7650                 throw misMatchedTypes("iterator parameters", itype, expected);
7651             }
7652         } else {
7653             if (externalParamList.isEmpty()) {
7654                 // special case; if the iterator handle is null and the body handle
7655                 // only declares V and T then the external parameter list consists
7656                 // of Iterable
7657                 externalParamList = Arrays.asList(Iterable.class);
7658                 iterableType = Iterable.class;
7659             } else {
7660                 // special case; if the iterator handle is null and the external
7661                 // parameter list is not empty then the first parameter must be
7662                 // assignable to Iterable
7663                 iterableType = externalParamList.get(0);
7664                 if (!Iterable.class.isAssignableFrom(iterableType)) {
7665                     throw newIllegalArgumentException(
7666                             "inferred first loop argument must inherit from Iterable: " + iterableType);
7667                 }
7668             }
7669         }
7670         if (init != null) {
7671             MethodType initType = init.type();
7672             if (initType.returnType() != returnType ||
7673                     !initType.effectivelyIdenticalParameters(0, externalParamList)) {
7674                 throw misMatchedTypes("loop initializer", initType, methodType(returnType, externalParamList));
7675             }
7676         }
7677         return iterableType;  // help the caller a bit
7678     }
7679 
7680     /*non-public*/
7681     static MethodHandle swapArguments(MethodHandle mh, int i, int j) {
7682         // there should be a better way to uncross my wires
7683         int arity = mh.type().parameterCount();
7684         int[] order = new int[arity];
7685         for (int k = 0; k < arity; k++)  order[k] = k;
7686         order[i] = j; order[j] = i;
7687         Class<?>[] types = mh.type().parameterArray();
7688         Class<?> ti = types[i]; types[i] = types[j]; types[j] = ti;
7689         MethodType swapType = methodType(mh.type().returnType(), types);
7690         return permuteArguments(mh, swapType, order);
7691     }
7692 
7693     /**
7694      * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block.
7695      * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception
7696      * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The
7697      * exception will be rethrown, unless {@code cleanup} handle throws an exception first.  The
7698      * value returned from the {@code cleanup} handle's execution will be the result of the execution of the
7699      * {@code try-finally} handle.
7700      * <p>
7701      * The {@code cleanup} handle will be passed one or two additional leading arguments.
7702      * The first is the exception thrown during the
7703      * execution of the {@code target} handle, or {@code null} if no exception was thrown.
7704      * The second is the result of the execution of the {@code target} handle, or, if it throws an exception,
7705      * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder.
7706      * The second argument is not present if the {@code target} handle has a {@code void} return type.
7707      * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists
7708      * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.)
7709      * <p>
7710      * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except
7711      * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or
7712      * two extra leading parameters:<ul>
7713      * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and
7714      * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry
7715      * the result from the execution of the {@code target} handle.
7716      * This parameter is not present if the {@code target} returns {@code void}.
7717      * </ul>
7718      * <p>
7719      * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of
7720      * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting
7721      * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by
7722      * the cleanup.
7723      * <blockquote><pre>{@code
7724      * V target(A..., B...);
7725      * V cleanup(Throwable, V, A...);
7726      * V adapter(A... a, B... b) {
7727      *   V result = (zero value for V);
7728      *   Throwable throwable = null;
7729      *   try {
7730      *     result = target(a..., b...);
7731      *   } catch (Throwable t) {
7732      *     throwable = t;
7733      *     throw t;
7734      *   } finally {
7735      *     result = cleanup(throwable, result, a...);
7736      *   }
7737      *   return result;
7738      * }
7739      * }</pre></blockquote>
7740      * <p>
7741      * Note that the saved arguments ({@code a...} in the pseudocode) cannot
7742      * be modified by execution of the target, and so are passed unchanged
7743      * from the caller to the cleanup, if it is invoked.
7744      * <p>
7745      * The target and cleanup must return the same type, even if the cleanup
7746      * always throws.
7747      * To create such a throwing cleanup, compose the cleanup logic
7748      * with {@link #throwException throwException},
7749      * in order to create a method handle of the correct return type.
7750      * <p>
7751      * Note that {@code tryFinally} never converts exceptions into normal returns.
7752      * In rare cases where exceptions must be converted in that way, first wrap
7753      * the target with {@link #catchException(MethodHandle, Class, MethodHandle)}
7754      * to capture an outgoing exception, and then wrap with {@code tryFinally}.
7755      * <p>
7756      * It is recommended that the first parameter type of {@code cleanup} be
7757      * declared {@code Throwable} rather than a narrower subtype.  This ensures
7758      * {@code cleanup} will always be invoked with whatever exception that
7759      * {@code target} throws.  Declaring a narrower type may result in a
7760      * {@code ClassCastException} being thrown by the {@code try-finally}
7761      * handle if the type of the exception thrown by {@code target} is not
7762      * assignable to the first parameter type of {@code cleanup}.  Note that
7763      * various exception types of {@code VirtualMachineError},
7764      * {@code LinkageError}, and {@code RuntimeException} can in principle be
7765      * thrown by almost any kind of Java code, and a finally clause that
7766      * catches (say) only {@code IOException} would mask any of the others
7767      * behind a {@code ClassCastException}.
7768      *
7769      * @param target the handle whose execution is to be wrapped in a {@code try} block.
7770      * @param cleanup the handle that is invoked in the finally block.
7771      *
7772      * @return a method handle embodying the {@code try-finally} block composed of the two arguments.
7773      * @throws NullPointerException if any argument is null
7774      * @throws IllegalArgumentException if {@code cleanup} does not accept
7775      *          the required leading arguments, or if the method handle types do
7776      *          not match in their return types and their
7777      *          corresponding trailing parameters
7778      *
7779      * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle)
7780      * @since 9
7781      */
7782     public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) {
7783         List<Class<?>> targetParamTypes = target.type().parameterList();
7784         Class<?> rtype = target.type().returnType();
7785 
7786         tryFinallyChecks(target, cleanup);
7787 
7788         // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments.
7789         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7790         // target parameter list.
7791         cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0);
7792 
7793         // Ensure that the intrinsic type checks the instance thrown by the
7794         // target against the first parameter of cleanup
7795         cleanup = cleanup.asType(cleanup.type().changeParameterType(0, Throwable.class));
7796 
7797         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
7798         return MethodHandleImpl.makeTryFinally(target.asFixedArity(), cleanup.asFixedArity(), rtype, targetParamTypes);
7799     }
7800 
7801     private static void tryFinallyChecks(MethodHandle target, MethodHandle cleanup) {
7802         Class<?> rtype = target.type().returnType();
7803         if (rtype != cleanup.type().returnType()) {
7804             throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype);
7805         }
7806         MethodType cleanupType = cleanup.type();
7807         if (!Throwable.class.isAssignableFrom(cleanupType.parameterType(0))) {
7808             throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class);
7809         }
7810         if (rtype != void.class && cleanupType.parameterType(1) != rtype) {
7811             throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype);
7812         }
7813         // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the
7814         // target parameter list.
7815         int cleanupArgIndex = rtype == void.class ? 1 : 2;
7816         if (!cleanupType.effectivelyIdenticalParameters(cleanupArgIndex, target.type().parameterList())) {
7817             throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix",
7818                     cleanup.type(), target.type());
7819         }
7820     }
7821 
7822     /**
7823      * Creates a table switch method handle, which can be used to switch over a set of target
7824      * method handles, based on a given target index, called selector.
7825      * <p>
7826      * For a selector value of {@code n}, where {@code n} falls in the range {@code [0, N)},
7827      * and where {@code N} is the number of target method handles, the table switch method
7828      * handle will invoke the n-th target method handle from the list of target method handles.
7829      * <p>
7830      * For a selector value that does not fall in the range {@code [0, N)}, the table switch
7831      * method handle will invoke the given fallback method handle.
7832      * <p>
7833      * All method handles passed to this method must have the same type, with the additional
7834      * requirement that the leading parameter be of type {@code int}. The leading parameter
7835      * represents the selector.
7836      * <p>
7837      * Any trailing parameters present in the type will appear on the returned table switch
7838      * method handle as well. Any arguments assigned to these parameters will be forwarded,
7839      * together with the selector value, to the selected method handle when invoking it.
7840      *
7841      * @apiNote Example:
7842      * The cases each drop the {@code selector} value they are given, and take an additional
7843      * {@code String} argument, which is concatenated (using {@link String#concat(String)})
7844      * to a specific constant label string for each case:
7845      * <blockquote><pre>{@code
7846      * MethodHandles.Lookup lookup = MethodHandles.lookup();
7847      * MethodHandle caseMh = lookup.findVirtual(String.class, "concat",
7848      *         MethodType.methodType(String.class, String.class));
7849      * caseMh = MethodHandles.dropArguments(caseMh, 0, int.class);
7850      *
7851      * MethodHandle caseDefault = MethodHandles.insertArguments(caseMh, 1, "default: ");
7852      * MethodHandle case0 = MethodHandles.insertArguments(caseMh, 1, "case 0: ");
7853      * MethodHandle case1 = MethodHandles.insertArguments(caseMh, 1, "case 1: ");
7854      *
7855      * MethodHandle mhSwitch = MethodHandles.tableSwitch(
7856      *     caseDefault,
7857      *     case0,
7858      *     case1
7859      * );
7860      *
7861      * assertEquals("default: data", (String) mhSwitch.invokeExact(-1, "data"));
7862      * assertEquals("case 0: data", (String) mhSwitch.invokeExact(0, "data"));
7863      * assertEquals("case 1: data", (String) mhSwitch.invokeExact(1, "data"));
7864      * assertEquals("default: data", (String) mhSwitch.invokeExact(2, "data"));
7865      * }</pre></blockquote>
7866      *
7867      * @param fallback the fallback method handle that is called when the selector is not
7868      *                 within the range {@code [0, N)}.
7869      * @param targets array of target method handles.
7870      * @return the table switch method handle.
7871      * @throws NullPointerException if {@code fallback}, the {@code targets} array, or any
7872      *                              any of the elements of the {@code targets} array are
7873      *                              {@code null}.
7874      * @throws IllegalArgumentException if the {@code targets} array is empty, if the leading
7875      *                                  parameter of the fallback handle or any of the target
7876      *                                  handles is not {@code int}, or if the types of
7877      *                                  the fallback handle and all of target handles are
7878      *                                  not the same.
7879      */
7880     public static MethodHandle tableSwitch(MethodHandle fallback, MethodHandle... targets) {
7881         Objects.requireNonNull(fallback);
7882         Objects.requireNonNull(targets);
7883         targets = targets.clone();
7884         MethodType type = tableSwitchChecks(fallback, targets);
7885         return MethodHandleImpl.makeTableSwitch(type, fallback, targets);
7886     }
7887 
7888     private static MethodType tableSwitchChecks(MethodHandle defaultCase, MethodHandle[] caseActions) {
7889         if (caseActions.length == 0)
7890             throw new IllegalArgumentException("Not enough cases: " + Arrays.toString(caseActions));
7891 
7892         MethodType expectedType = defaultCase.type();
7893 
7894         if (!(expectedType.parameterCount() >= 1) || expectedType.parameterType(0) != int.class)
7895             throw new IllegalArgumentException(
7896                 "Case actions must have int as leading parameter: " + Arrays.toString(caseActions));
7897 
7898         for (MethodHandle mh : caseActions) {
7899             Objects.requireNonNull(mh);
7900             if (mh.type() != expectedType)
7901                 throw new IllegalArgumentException(
7902                     "Case actions must have the same type: " + Arrays.toString(caseActions));
7903         }
7904 
7905         return expectedType;
7906     }
7907 
7908 }