1 /*
   2  * Copyright (c) 1999, 2023, 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.reflect;
  27 
  28 import java.lang.invoke.MethodHandle;
  29 import java.lang.invoke.MethodHandles;
  30 import java.lang.invoke.MethodType;
  31 import java.lang.invoke.WrongMethodTypeException;
  32 import java.lang.module.ModuleDescriptor;
  33 import java.security.AccessController;
  34 import java.security.PrivilegedAction;
  35 import java.util.ArrayDeque;
  36 import java.util.Arrays;
  37 import java.util.Collections;
  38 import java.util.Deque;
  39 import java.util.HashMap;
  40 import java.util.HashSet;
  41 import java.util.IdentityHashMap;
  42 import java.util.List;
  43 import java.util.Map;
  44 import java.util.Objects;
  45 import java.util.Set;
  46 import java.util.concurrent.ConcurrentHashMap;
  47 import java.util.concurrent.atomic.AtomicInteger;
  48 import java.util.concurrent.atomic.AtomicLong;
  49 import java.util.function.BooleanSupplier;
  50 
  51 import jdk.internal.access.JavaLangAccess;
  52 import jdk.internal.access.SharedSecrets;
  53 import jdk.internal.value.PrimitiveClass;
  54 import jdk.internal.module.Modules;
  55 import jdk.internal.misc.VM;
  56 import jdk.internal.reflect.CallerSensitive;
  57 import jdk.internal.reflect.Reflection;
  58 import jdk.internal.loader.ClassLoaderValue;
  59 import jdk.internal.vm.annotation.Stable;
  60 import sun.reflect.misc.ReflectUtil;
  61 import sun.security.action.GetPropertyAction;
  62 import sun.security.util.SecurityConstants;
  63 
  64 import static java.lang.invoke.MethodType.methodType;
  65 import static java.lang.module.ModuleDescriptor.Modifier.SYNTHETIC;
  66 
  67 /**
  68  *
  69  * {@code Proxy} provides static methods for creating objects that act like instances
  70  * of interfaces but allow for customized method invocation.
  71  * To create a proxy instance for some interface {@code Foo}:
  72  * <pre>{@code
  73  *     InvocationHandler handler = new MyInvocationHandler(...);
  74  *     Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
  75  *                                          new Class<?>[] { Foo.class },
  76  *                                          handler);
  77  * }</pre>
  78  *
  79  * <p>
  80  * A <em>proxy class</em> is a class created at runtime that implements a specified
  81  * list of interfaces, known as <em>proxy interfaces</em>. A <em>proxy instance</em>
  82  * is an instance of a proxy class.
  83  *
  84  * Each proxy instance has an associated <i>invocation handler</i>
  85  * object, which implements the interface {@link InvocationHandler}.
  86  * A method invocation on a proxy instance through one of its proxy
  87  * interfaces will be dispatched to the {@link InvocationHandler#invoke
  88  * invoke} method of the instance's invocation handler, passing the proxy
  89  * instance, a {@code java.lang.reflect.Method} object identifying
  90  * the method that was invoked, and an array of type {@code Object}
  91  * containing the arguments.  The invocation handler processes the
  92  * encoded method invocation as appropriate and the result that it
  93  * returns will be returned as the result of the method invocation on
  94  * the proxy instance.
  95  *
  96  * <p>A proxy class has the following properties:
  97  *
  98  * <ul>
  99  * <li>The unqualified name of a proxy class is unspecified.  The space
 100  * of class names that begin with the string {@code "$Proxy"}
 101  * should be, however, reserved for proxy classes.
 102  *
 103  * <li>The package and module in which a proxy class is defined is specified
 104  * <a href="#membership">below</a>.
 105  *
 106  * <li>A proxy class is <em>final and non-abstract</em>.
 107  *
 108  * <li>A proxy class extends {@code java.lang.reflect.Proxy}.
 109  *
 110  * <li>A proxy class implements exactly the interfaces specified at its
 111  * creation, in the same order. Invoking {@link Class#getInterfaces() getInterfaces}
 112  * on its {@code Class} object will return an array containing the same
 113  * list of interfaces (in the order specified at its creation), invoking
 114  * {@link Class#getMethods getMethods} on its {@code Class} object will return
 115  * an array of {@code Method} objects that include all of the
 116  * methods in those interfaces, and invoking {@code getMethod} will
 117  * find methods in the proxy interfaces as would be expected.
 118  *
 119  * <li>The {@link java.security.ProtectionDomain} of a proxy class
 120  * is the same as that of system classes loaded by the bootstrap class
 121  * loader, such as {@code java.lang.Object}, because the code for a
 122  * proxy class is generated by trusted system code.  This protection
 123  * domain will typically be granted {@code java.security.AllPermission}.
 124  *
 125  * <li>The {@link Proxy#isProxyClass Proxy.isProxyClass} method can be used
 126  * to determine if a given class is a proxy class.
 127  * </ul>
 128  *
 129  * <p>A proxy instance has the following properties:
 130  *
 131  * <ul>
 132  * <li>Given a proxy instance {@code proxy} and one of the
 133  * interfaces, {@code Foo}, implemented by its proxy class, the
 134  * following expression will return true:
 135  * <pre>
 136  *     {@code proxy instanceof Foo}
 137  * </pre>
 138  * and the following cast operation will succeed (rather than throwing
 139  * a {@code ClassCastException}):
 140  * <pre>
 141  *     {@code (Foo) proxy}
 142  * </pre>
 143  *
 144  * <li>Each proxy instance has an associated invocation handler, the one
 145  * that was passed to its constructor.  The static
 146  * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method
 147  * will return the invocation handler associated with the proxy instance
 148  * passed as its argument.
 149  *
 150  * <li>An interface method invocation on a proxy instance will be
 151  * encoded and dispatched to the invocation handler's {@link
 152  * InvocationHandler#invoke invoke} method as described in the
 153  * documentation for that method.
 154  *
 155  * <li>A proxy interface may define a default method or inherit
 156  * a default method from its superinterface directly or indirectly.
 157  * An invocation handler can invoke a default method of a proxy interface
 158  * by calling {@link InvocationHandler#invokeDefault(Object, Method, Object...)
 159  * InvocationHandler::invokeDefault}.
 160  *
 161  * <li>An invocation of the {@code hashCode},
 162  * {@code equals}, or {@code toString} methods declared in
 163  * {@code java.lang.Object} on a proxy instance will be encoded and
 164  * dispatched to the invocation handler's {@code invoke} method in
 165  * the same manner as interface method invocations are encoded and
 166  * dispatched, as described above.  The declaring class of the
 167  * {@code Method} object passed to {@code invoke} will be
 168  * {@code java.lang.Object}.  Other public methods of a proxy
 169  * instance inherited from {@code java.lang.Object} are not
 170  * overridden by a proxy class, so invocations of those methods behave
 171  * like they do for instances of {@code java.lang.Object}.
 172  * </ul>
 173  *
 174  * <h2><a id="membership">Package and Module Membership of Proxy Class</a></h2>
 175  *
 176  * The package and module to which a proxy class belongs are chosen such that
 177  * the accessibility of the proxy class is in line with the accessibility of
 178  * the proxy interfaces. Specifically, the package and the module membership
 179  * of a proxy class defined via the
 180  * {@link Proxy#getProxyClass(ClassLoader, Class[])} or
 181  * {@link Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)}
 182  * methods is specified as follows:
 183  *
 184  * <ol>
 185  * <li>If all the proxy interfaces are in <em>exported</em> or <em>open</em>
 186  *     packages:
 187  * <ol type="a">
 188  * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is
 189  *     <em>public</em> in an unconditionally exported but non-open package.
 190  *     The name of the package and the module are unspecified.</li>
 191  *
 192  * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then
 193  *     the proxy class is <em>non-public</em> in the package and module of the
 194  *     non-public interfaces. All the non-public interfaces must be in the same
 195  *     package and module; otherwise, proxying them is
 196  *     <a href="#restrictions">not possible</a>.</li>
 197  * </ol>
 198  * </li>
 199  * <li>If at least one proxy interface is in a package that is
 200  *     <em>non-exported</em> and <em>non-open</em>:
 201  * <ol type="a">
 202  * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is
 203  *     <em>public</em> in a <em>non-exported</em>, <em>non-open</em> package of
 204  *     <a href="#dynamicmodule"><em>dynamic module</em>.</a>
 205  *     The names of the package and the module are unspecified.</li>
 206  *
 207  * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then
 208  *     the proxy class is <em>non-public</em> in the package and module of the
 209  *     non-public interfaces. All the non-public interfaces must be in the same
 210  *     package and module; otherwise, proxying them is
 211  *     <a href="#restrictions">not possible</a>.</li>
 212  * </ol>
 213  * </li>
 214  * </ol>
 215  *
 216  * <p>
 217  * Note that if proxy interfaces with a mix of accessibilities -- for example,
 218  * an exported public interface and a non-exported non-public interface -- are
 219  * proxied by the same instance, then the proxy class's accessibility is
 220  * governed by the least accessible proxy interface.
 221  * <p>
 222  * Note that it is possible for arbitrary code to obtain access to a proxy class
 223  * in an open package with {@link AccessibleObject#setAccessible setAccessible},
 224  * whereas a proxy class in a non-open package is never accessible to
 225  * code outside the module of the proxy class.
 226  *
 227  * <p>
 228  * Throughout this specification, a "non-exported package" refers to a package
 229  * that is not exported to all modules, and a "non-open package" refers to
 230  * a package that is not open to all modules.  Specifically, these terms refer to
 231  * a package that either is not exported/open by its containing module or is
 232  * exported/open in a qualified fashion by its containing module.
 233  *
 234  * <h3><a id="dynamicmodule">Dynamic Modules</a></h3>
 235  * <p>
 236  * A dynamic module is a named module generated at runtime. A proxy class
 237  * defined in a dynamic module is encapsulated and not accessible to any module.
 238  * Calling {@link Constructor#newInstance(Object...)} on a proxy class in
 239  * a dynamic module will throw {@code IllegalAccessException};
 240  * {@code Proxy.newProxyInstance} method should be used instead.
 241  *
 242  * <p>
 243  * A dynamic module can read the modules of all of the superinterfaces of a proxy
 244  * class and the modules of the classes and interfaces referenced by
 245  * all public method signatures of a proxy class.  If a superinterface or
 246  * a referenced class or interface, say {@code T}, is in a non-exported package,
 247  * the {@linkplain Module module} of {@code T} is updated to export the
 248  * package of {@code T} to the dynamic module.
 249  *
 250  * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3>
 251  *
 252  * <p>When two or more proxy interfaces contain a method with
 253  * the same name and parameter signature, the order of the proxy class's
 254  * interfaces becomes significant.  When such a <i>duplicate method</i>
 255  * is invoked on a proxy instance, the {@code Method} object passed
 256  * to the invocation handler will not necessarily be the one whose
 257  * declaring class is assignable from the reference type of the interface
 258  * that the proxy's method was invoked through.  This limitation exists
 259  * because the corresponding method implementation in the generated proxy
 260  * class cannot determine which interface it was invoked through.
 261  * Therefore, when a duplicate method is invoked on a proxy instance,
 262  * the {@code Method} object for the method in the foremost interface
 263  * that contains the method (either directly or inherited through a
 264  * superinterface) in the proxy class's list of interfaces is passed to
 265  * the invocation handler's {@code invoke} method, regardless of the
 266  * reference type through which the method invocation occurred.
 267  *
 268  * <p>If a proxy interface contains a method with the same name and
 269  * parameter signature as the {@code hashCode}, {@code equals},
 270  * or {@code toString} methods of {@code java.lang.Object},
 271  * when such a method is invoked on a proxy instance, the
 272  * {@code Method} object passed to the invocation handler will have
 273  * {@code java.lang.Object} as its declaring class.  In other words,
 274  * the public, non-final methods of {@code java.lang.Object}
 275  * logically precede all of the proxy interfaces for the determination of
 276  * which {@code Method} object to pass to the invocation handler.
 277  *
 278  * <p>Note also that when a duplicate method is dispatched to an
 279  * invocation handler, the {@code invoke} method may only throw
 280  * checked exception types that are assignable to one of the exception
 281  * types in the {@code throws} clause of the method in <i>all</i> of
 282  * the proxy interfaces that it can be invoked through.  If the
 283  * {@code invoke} method throws a checked exception that is not
 284  * assignable to any of the exception types declared by the method in one
 285  * of the proxy interfaces that it can be invoked through, then an
 286  * unchecked {@code UndeclaredThrowableException} will be thrown by
 287  * the invocation on the proxy instance.  This restriction means that not
 288  * all of the exception types returned by invoking
 289  * {@code getExceptionTypes} on the {@code Method} object
 290  * passed to the {@code invoke} method can necessarily be thrown
 291  * successfully by the {@code invoke} method.
 292  *
 293  * @author      Peter Jones
 294  * @see         InvocationHandler
 295  * @since       1.3
 296  * @revised 9
 297  */
 298 public class Proxy implements java.io.Serializable {
 299     @java.io.Serial
 300     private static final long serialVersionUID = -2222568056686623797L;
 301 
 302     /** parameter types of a proxy class constructor */
 303     private static final Class<?>[] constructorParams =
 304         { InvocationHandler.class };
 305 
 306     /**
 307      * a cache of proxy constructors with
 308      * {@link Constructor#setAccessible(boolean) accessible} flag already set
 309      */
 310     private static final ClassLoaderValue<Constructor<?>> proxyCache =
 311         new ClassLoaderValue<>();
 312 
 313     /**
 314      * the invocation handler for this proxy instance.
 315      * @serial
 316      */
 317     @SuppressWarnings("serial") // Not statically typed as Serializable
 318     protected InvocationHandler h;
 319 
 320     /**
 321      * Prohibits instantiation.
 322      */
 323     private Proxy() {
 324     }
 325 
 326     /**
 327      * Constructs a new {@code Proxy} instance from a subclass
 328      * (typically, a dynamic proxy class) with the specified value
 329      * for its invocation handler.
 330      *
 331      * @param  h the invocation handler for this proxy instance
 332      *
 333      * @throws NullPointerException if the given invocation handler, {@code h},
 334      *         is {@code null}.
 335      */
 336     protected Proxy(InvocationHandler h) {
 337         Objects.requireNonNull(h);
 338         this.h = h;
 339     }
 340 
 341     /**
 342      * Returns the {@code java.lang.Class} object for a proxy class
 343      * given a class loader and an array of interfaces.  The proxy class
 344      * will be defined by the specified class loader and will implement
 345      * all of the supplied interfaces.  If any of the given interfaces
 346      * is non-public, the proxy class will be non-public. If a proxy class
 347      * for the same permutation of interfaces has already been defined by the
 348      * class loader, then the existing proxy class will be returned; otherwise,
 349      * a proxy class for those interfaces will be generated dynamically
 350      * and defined by the class loader.
 351      *
 352      * @param   loader the class loader to define the proxy class
 353      * @param   interfaces the list of interfaces for the proxy class
 354      *          to implement
 355      * @return  a proxy class that is defined in the specified class loader
 356      *          and that implements the specified interfaces
 357      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
 358      *          restrictions</a> on the parameters are violated
 359      * @throws  SecurityException if a security manager, <em>s</em>, is present
 360      *          and any of the following conditions is met:
 361      *          <ul>
 362      *             <li> the given {@code loader} is {@code null} and
 363      *             the caller's class loader is not {@code null} and the
 364      *             invocation of {@link SecurityManager#checkPermission
 365      *             s.checkPermission} with
 366      *             {@code RuntimePermission("getClassLoader")} permission
 367      *             denies access.</li>
 368      *             <li> for each proxy interface, {@code intf},
 369      *             the caller's class loader is not the same as or an
 370      *             ancestor of the class loader for {@code intf} and
 371      *             invocation of {@link SecurityManager#checkPackageAccess
 372      *             s.checkPackageAccess()} denies access to {@code intf}.</li>
 373      *          </ul>
 374      * @throws  NullPointerException if the {@code interfaces} array
 375      *          argument or any of its elements are {@code null}
 376      *
 377      * @deprecated Proxy classes generated in a named module are encapsulated
 378      *      and not accessible to code outside its module.
 379      *      {@link Constructor#newInstance(Object...) Constructor.newInstance}
 380      *      will throw {@code IllegalAccessException} when it is called on
 381      *      an inaccessible proxy class.
 382      *      Use {@link #newProxyInstance(ClassLoader, Class[], InvocationHandler)}
 383      *      to create a proxy instance instead.
 384      *
 385      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
 386      * @revised 9
 387      */
 388     @Deprecated
 389     @CallerSensitive
 390     public static Class<?> getProxyClass(ClassLoader loader,
 391                                          Class<?>... interfaces)
 392         throws IllegalArgumentException
 393     {
 394         @SuppressWarnings("removal")
 395         Class<?> caller = System.getSecurityManager() == null
 396                               ? null
 397                               : Reflection.getCallerClass();
 398 
 399         return getProxyConstructor(caller, loader, interfaces)
 400             .getDeclaringClass();
 401     }
 402 
 403     /**
 404      * Returns the {@code Constructor} object of a proxy class that takes a
 405      * single argument of type {@link InvocationHandler}, given a class loader
 406      * and an array of interfaces. The returned constructor will have the
 407      * {@link Constructor#setAccessible(boolean) accessible} flag already set.
 408      *
 409      * @param   caller passed from a public-facing @CallerSensitive method if
 410      *                 SecurityManager is set or {@code null} if there's no
 411      *                 SecurityManager
 412      * @param   loader the class loader to define the proxy class
 413      * @param   interfaces the list of interfaces for the proxy class
 414      *          to implement
 415      * @return  a Constructor of the proxy class taking single
 416      *          {@code InvocationHandler} parameter
 417      */
 418     private static Constructor<?> getProxyConstructor(Class<?> caller,
 419                                                       ClassLoader loader,
 420                                                       Class<?>... interfaces)
 421     {
 422         // optimization for single interface
 423         if (interfaces.length == 1) {
 424             Class<?> intf = interfaces[0];
 425             if (caller != null) {
 426                 checkProxyAccess(caller, loader, intf);
 427             }
 428             return proxyCache.sub(intf).computeIfAbsent(
 429                 loader,
 430                 (ld, clv) -> new ProxyBuilder(ld, clv.key()).build()
 431             );
 432         } else {
 433             // interfaces cloned
 434             final Class<?>[] intfsArray = interfaces.clone();
 435             if (caller != null) {
 436                 checkProxyAccess(caller, loader, intfsArray);
 437             }
 438             final List<Class<?>> intfs = Arrays.asList(intfsArray);
 439             return proxyCache.sub(intfs).computeIfAbsent(
 440                 loader,
 441                 (ld, clv) -> new ProxyBuilder(ld, clv.key()).build()
 442             );
 443         }
 444     }
 445 
 446     /*
 447      * Check permissions required to create a Proxy class.
 448      *
 449      * To define a proxy class, it performs the access checks as in
 450      * Class.forName (VM will invoke ClassLoader.checkPackageAccess):
 451      * 1. "getClassLoader" permission check if loader == null
 452      * 2. checkPackageAccess on the interfaces it implements
 453      *
 454      * To get a constructor and new instance of a proxy class, it performs
 455      * the package access check on the interfaces it implements
 456      * as in Class.getConstructor.
 457      *
 458      * If an interface is non-public, the proxy class must be defined by
 459      * the defining loader of the interface.  If the caller's class loader
 460      * is not the same as the defining loader of the interface, the VM
 461      * will throw IllegalAccessError when the generated proxy class is
 462      * being defined.
 463      */
 464     private static void checkProxyAccess(Class<?> caller,
 465                                          ClassLoader loader,
 466                                          Class<?> ... interfaces)
 467     {
 468         @SuppressWarnings("removal")
 469         SecurityManager sm = System.getSecurityManager();
 470         if (sm != null) {
 471             ClassLoader ccl = caller.getClassLoader();
 472             if (loader == null && ccl != null) {
 473                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 474             }
 475             ReflectUtil.checkProxyPackageAccess(ccl, interfaces);
 476         }
 477     }
 478 
 479     /**
 480      * Builder for a proxy class.
 481      *
 482      * If the module is not specified in this ProxyBuilder constructor,
 483      * it will map from the given loader and interfaces to the module
 484      * in which the proxy class will be defined.
 485      */
 486     private static final class ProxyBuilder {
 487         private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
 488 
 489         // prefix for all proxy class names
 490         private static final String proxyClassNamePrefix = "$Proxy";
 491 
 492         // next number to use for generation of unique proxy class names
 493         private static final AtomicLong nextUniqueNumber = new AtomicLong();
 494 
 495         // a reverse cache of defined proxy classes
 496         private static final ClassLoaderValue<Boolean> reverseProxyCache =
 497             new ClassLoaderValue<>();
 498 
 499         private record ProxyClassContext(Module module, String packageName, int accessFlags) {
 500             private ProxyClassContext {
 501                 if (module.isNamed()) {
 502                     if (packageName.isEmpty()) {
 503                         // Per JLS 7.4.2, unnamed package can only exist in unnamed modules.
 504                         // This means a package-private superinterface exist in the unnamed
 505                         // package of a named module.
 506                         throw new InternalError("Unnamed package cannot be added to " + module);
 507                     }
 508 
 509                     if (!module.getDescriptor().packages().contains(packageName)) {
 510                         throw new InternalError(packageName + " not exist in " + module.getName());
 511                     }
 512 
 513                     if (!module.isOpen(packageName, Proxy.class.getModule())) {
 514                         // Required for default method invocation
 515                         throw new InternalError(packageName + " not open to " + Proxy.class.getModule());
 516                     }
 517                 } else {
 518                     if (Modifier.isPublic(accessFlags)) {
 519                         // All proxy superinterfaces are public, must be in named dynamic module
 520                         throw new InternalError("public proxy in unnamed module: " + module);
 521                     }
 522                 }
 523 
 524                 if ((accessFlags & ~(Modifier.PUBLIC | Modifier.IDENTITY)) != 0) {
 525                     throw new InternalError("proxy access flags must be Modifier.PUBLIC or 0");
 526                 }
 527             }
 528         }
 529 
 530         private static Class<?> defineProxyClass(ProxyClassContext context, List<Class<?>> interfaces) {
 531             /*
 532              * Choose a name for the proxy class to generate.
 533              */
 534             long num = nextUniqueNumber.getAndIncrement();
 535             String proxyName = context.packageName().isEmpty()
 536                                     ? proxyClassNamePrefix + num
 537                                     : context.packageName() + "." + proxyClassNamePrefix + num;
 538 
 539             ClassLoader loader = getLoader(context.module());
 540             trace(proxyName, context.module(), loader, interfaces);
 541 
 542             /*
 543              * Generate the specified proxy class.
 544              */
 545             byte[] proxyClassFile = ProxyGenerator.generateProxyClass(loader, proxyName, interfaces,
 546                                                                       context.accessFlags() | Modifier.FINAL | Modifier.IDENTITY);
 547             try {
 548                 Class<?> pc = JLA.defineClass(loader, proxyName, proxyClassFile,
 549                                               null, "__dynamic_proxy__");
 550                 reverseProxyCache.sub(pc).putIfAbsent(loader, Boolean.TRUE);
 551                 return pc;
 552             } catch (ClassFormatError e) {
 553                 /*
 554                  * A ClassFormatError here means that (barring bugs in the
 555                  * proxy class generation code) there was some other
 556                  * invalid aspect of the arguments supplied to the proxy
 557                  * class creation (such as virtual machine limitations
 558                  * exceeded).
 559                  */
 560                 throw new IllegalArgumentException(e.toString());
 561             }
 562         }
 563 
 564         /**
 565          * Test if given class is a class defined by
 566          * {@link #defineProxyClass(ProxyClassContext, List)}
 567          */
 568         static boolean isProxyClass(Class<?> c) {
 569             return Objects.equals(reverseProxyCache.sub(c).get(c.getClassLoader()),
 570                                   Boolean.TRUE);
 571         }
 572 
 573         private static boolean isExportedType(Class<?> c) {
 574             String pn = c.getPackageName();
 575             return Modifier.isPublic(c.getModifiers()) && c.getModule().isExported(pn);
 576         }
 577 
 578         private static boolean isPackagePrivateType(Class<?> c) {
 579             return !Modifier.isPublic(c.getModifiers());
 580         }
 581 
 582         private static String toDetails(Class<?> c) {
 583             String access = "unknown";
 584             if (isExportedType(c)) {
 585                 access = "exported";
 586             } else if (isPackagePrivateType(c)) {
 587                 access = "package-private";
 588             } else {
 589                 access = "module-private";
 590             }
 591             ClassLoader ld = c.getClassLoader();
 592             return String.format("   %s/%s %s loader %s",
 593                     c.getModule().getName(), c.getName(), access, ld);
 594         }
 595 
 596         static void trace(String cn,
 597                           Module module,
 598                           ClassLoader loader,
 599                           List<Class<?>> interfaces) {
 600             if (isDebug()) {
 601                 System.err.format("PROXY: %s/%s defined by %s%n",
 602                                   module.getName(), cn, loader);
 603             }
 604             if (isDebug("debug")) {
 605                 interfaces.forEach(c -> System.out.println(toDetails(c)));
 606             }
 607         }
 608 
 609         private static final String DEBUG =
 610             GetPropertyAction.privilegedGetProperty("jdk.proxy.debug", "");
 611 
 612         private static boolean isDebug() {
 613             return !DEBUG.isEmpty();
 614         }
 615         private static boolean isDebug(String flag) {
 616             return DEBUG.equals(flag);
 617         }
 618 
 619         // ProxyBuilder instance members start here....
 620 
 621         private final List<Class<?>> interfaces;
 622         private final ProxyClassContext context;
 623         ProxyBuilder(ClassLoader loader, List<Class<?>> interfaces) {
 624             if (!VM.isModuleSystemInited()) {
 625                 throw new InternalError("Proxy is not supported until "
 626                         + "module system is fully initialized");
 627             }
 628             if (interfaces.size() > 65535) {
 629                 throw new IllegalArgumentException("interface limit exceeded: "
 630                         + interfaces.size());
 631             }
 632 
 633             Set<Class<?>> refTypes = referencedTypes(loader, interfaces);
 634 
 635             // IAE if violates any restrictions specified in newProxyInstance
 636             validateProxyInterfaces(loader, interfaces, refTypes);
 637 
 638             this.interfaces = interfaces;
 639             this.context = proxyClassContext(loader, interfaces, refTypes);
 640             assert getLoader(context.module()) == loader;
 641         }
 642 
 643         ProxyBuilder(ClassLoader loader, Class<?> intf) {
 644             this(loader, Collections.singletonList(intf));
 645         }
 646 
 647         /**
 648          * Generate a proxy class and return its proxy Constructor with
 649          * accessible flag already set. If the target module does not have access
 650          * to any interface types, IllegalAccessError will be thrown by the VM
 651          * at defineClass time.
 652          *
 653          * Must call the checkProxyAccess method to perform permission checks
 654          * before calling this.
 655          */
 656         @SuppressWarnings("removal")
 657         Constructor<?> build() {
 658             Class<?> proxyClass = defineProxyClass(context, interfaces);
 659 
 660             final Constructor<?> cons;
 661             try {
 662                 cons = proxyClass.getConstructor(constructorParams);
 663             } catch (NoSuchMethodException e) {
 664                 throw new InternalError(e.toString(), e);
 665             }
 666             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 667                 public Void run() {
 668                     cons.setAccessible(true);
 669                     return null;
 670                 }
 671             });
 672             return cons;
 673         }
 674 
 675         /**
 676          * Validate the given proxy interfaces and the given referenced types
 677          * are visible to the defining loader.
 678          *
 679          * @throws IllegalArgumentException if it violates the restrictions
 680          *         specified in {@link Proxy#newProxyInstance}
 681          */
 682         private static void validateProxyInterfaces(ClassLoader loader,
 683                                                     List<Class<?>> interfaces,
 684                                                     Set<Class<?>> refTypes)
 685         {
 686             Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.size());
 687             for (Class<?> intf : interfaces) {
 688                 /*
 689                  * Verify that the Class object actually represents an
 690                  * interface.
 691                  */
 692                 if (!intf.isInterface()) {
 693                     throw new IllegalArgumentException(intf.getName() + " is not an interface");
 694                 }
 695 
 696                 if (intf.isHidden()) {
 697                     throw new IllegalArgumentException(intf.getName() + " is a hidden interface");
 698                 }
 699 
 700                 if (intf.isSealed()) {
 701                     throw new IllegalArgumentException(intf.getName() + " is a sealed interface");
 702                 }
 703 
 704                 /*
 705                  * Verify that the class loader resolves the name of this
 706                  * interface to the same Class object.
 707                  */
 708                 ensureVisible(loader, intf);
 709 
 710                 /*
 711                  * Verify that this interface is not a duplicate.
 712                  */
 713                 if (interfaceSet.put(intf, Boolean.TRUE) != null) {
 714                     throw new IllegalArgumentException("repeated interface: " + intf.getName());
 715                 }
 716             }
 717 
 718             for (Class<?> type : refTypes) {
 719                 ensureVisible(loader, type);
 720             }
 721         }
 722 
 723         /*
 724          * Returns all types referenced by all public non-static method signatures of
 725          * the proxy interfaces
 726          */
 727         private static Set<Class<?>> referencedTypes(ClassLoader loader,
 728                                                      List<Class<?>> interfaces) {
 729             var types = new HashSet<Class<?>>();
 730             for (var intf : interfaces) {
 731                 for (Method m : intf.getMethods()) {
 732                     if (!Modifier.isStatic(m.getModifiers())) {
 733                         addElementType(types, m.getReturnType());
 734                         addElementTypes(types, m.getSharedParameterTypes());
 735                         addElementTypes(types, m.getSharedExceptionTypes());
 736                     }
 737                 }
 738             }
 739             return types;
 740         }
 741 
 742         private static void addElementTypes(HashSet<Class<?>> types,
 743                                             Class<?> ... classes) {
 744             for (var cls : classes) {
 745                 addElementType(types, cls);
 746             }
 747         }
 748 
 749         private static void addElementType(HashSet<Class<?>> types,
 750                                            Class<?> cls) {
 751             var type = getElementType(cls);
 752             if (!type.isPrimitive()) {
 753                 types.add(type);
 754             }
 755         }
 756 
 757         /**
 758          * Returns the context for the generated proxy class, including the
 759          * module and the package it belongs to and whether it is package-private.
 760          *
 761          * If any of proxy interface is package-private, then the proxy class
 762          * is in the same package and module as the package-private interface.
 763          *
 764          * If all proxy interfaces are public and in exported packages,
 765          * then the proxy class is in a dynamic module in an unconditionally
 766          * exported package.
 767          *
 768          * If all proxy interfaces are public and at least one in a non-exported
 769          * package, then the proxy class is in a dynamic module in a
 770          * non-exported package.
 771          *
 772          * The package of proxy class is open to java.base for deep reflective access.
 773          *
 774          * Reads edge and qualified exports are added for dynamic module to access.
 775          */
 776         private static ProxyClassContext proxyClassContext(ClassLoader loader,
 777                                                            List<Class<?>> interfaces,
 778                                                            Set<Class<?>> refTypes) {
 779             Map<Class<?>, Module> packagePrivateTypes = new HashMap<>();
 780             boolean nonExported = false;
 781 
 782             for (Class<?> intf : interfaces) {
 783                 Module m = intf.getModule();
 784                 if (!Modifier.isPublic(intf.getModifiers())) {
 785                     packagePrivateTypes.put(intf, m);
 786                 } else {
 787                     if (!intf.getModule().isExported(intf.getPackageName())) {
 788                         // module-private types
 789                         nonExported = true;
 790                     }
 791                 }
 792             }
 793 
 794             if (packagePrivateTypes.size() > 0) {
 795                 // all package-private types must be in the same runtime package
 796                 // i.e. same package name and same module (named or unnamed)
 797                 //
 798                 // Configuration will fail if M1 and in M2 defined by the same loader
 799                 // and both have the same package p (so no need to check class loader)
 800                 Module targetModule = null;
 801                 String targetPackageName = null;
 802                 for (Map.Entry<Class<?>, Module> e : packagePrivateTypes.entrySet()) {
 803                     Class<?> intf = e.getKey();
 804                     Module m = e.getValue();
 805                     if ((targetModule != null && targetModule != m) ||
 806                         (targetPackageName != null && targetPackageName != intf.getPackageName())) {
 807                         throw new IllegalArgumentException(
 808                                 "cannot have non-public interfaces in different packages");
 809                     }
 810                     if (getLoader(m) != loader) {
 811                         // the specified loader is not the same class loader
 812                         // of the non-public interface
 813                         throw new IllegalArgumentException(
 814                                 "non-public interface is not defined by the given loader");
 815                     }
 816 
 817                     targetModule = m;
 818                     targetPackageName = e.getKey().getPackageName();
 819                 }
 820 
 821                 // validate if the target module can access all other interfaces
 822                 for (Class<?> intf : interfaces) {
 823                     Module m = intf.getModule();
 824                     if (m == targetModule) continue;
 825 
 826                     if (!targetModule.canRead(m) || !m.isExported(intf.getPackageName(), targetModule)) {
 827                         throw new IllegalArgumentException(targetModule + " can't access " + intf.getName());
 828                     }
 829                 }
 830 
 831                 // opens the package of the non-public proxy class for java.base to access
 832                 if (targetModule.isNamed()) {
 833                     Modules.addOpens(targetModule, targetPackageName, Proxy.class.getModule());
 834                 }
 835                 // return the module of the package-private interface
 836                 return new ProxyClassContext(targetModule, targetPackageName, 0);
 837             }
 838 
 839             // All proxy interfaces are public.  So maps to a dynamic proxy module
 840             // and add reads edge and qualified exports, if necessary
 841             Module targetModule = getDynamicModule(loader);
 842 
 843             // set up proxy class access to proxy interfaces and types
 844             // referenced in the method signature
 845             Set<Class<?>> types = new HashSet<>(interfaces);
 846             types.addAll(refTypes);
 847             for (Class<?> c : types) {
 848                 ensureAccess(targetModule, c);
 849             }
 850 
 851             var pkgName = nonExported ? PROXY_PACKAGE_PREFIX + '.' + targetModule.getName()
 852                                       : targetModule.getName();
 853             return new ProxyClassContext(targetModule, pkgName, Modifier.PUBLIC);
 854         }
 855 
 856         /*
 857          * Ensure the given module can access the given class.
 858          */
 859         private static void ensureAccess(Module target, Class<?> c) {
 860             Module m = c.getModule();
 861             // add read edge and qualified export for the target module to access
 862             if (!target.canRead(m)) {
 863                 Modules.addReads(target, m);
 864             }
 865             String pn = c.getPackageName();
 866             if (!m.isExported(pn, target)) {
 867                 Modules.addExports(m, pn, target);
 868             }
 869         }
 870 
 871         /*
 872          * Ensure the given class is visible to the class loader.
 873          */
 874         private static void ensureVisible(ClassLoader ld, Class<?> c) {
 875             Class<?> type = null;
 876             try {
 877                 type = Class.forName(c.getName(), false, ld);
 878             } catch (ClassNotFoundException e) {
 879             }
 880             if (PrimitiveClass.asPrimaryType(type) != PrimitiveClass.asPrimaryType(c)) {
 881                 throw new IllegalArgumentException(c.getName() +
 882                         " referenced from a method is not visible from class loader: " + JLA.getLoaderNameID(ld));
 883             }
 884         }
 885 
 886         private static Class<?> getElementType(Class<?> type) {
 887             Class<?> e = type;
 888             while (e.isArray()) {
 889                 e = e.getComponentType();
 890             }
 891             return e;
 892         }
 893 
 894         private static final ClassLoaderValue<Module> dynProxyModules =
 895             new ClassLoaderValue<>();
 896         private static final AtomicInteger counter = new AtomicInteger();
 897 
 898         /*
 899          * Define a dynamic module with a package named $MODULE which
 900          * is unconditionally exported and another package named
 901          * com.sun.proxy.$MODULE which is encapsulated.
 902          *
 903          * Each class loader will have one dynamic module.
 904          */
 905         private static Module getDynamicModule(ClassLoader loader) {
 906             return dynProxyModules.computeIfAbsent(loader, (ld, clv) -> {
 907                 // create a dynamic module and setup module access
 908                 String mn = "jdk.proxy" + counter.incrementAndGet();
 909                 String pn = PROXY_PACKAGE_PREFIX + "." + mn;
 910                 ModuleDescriptor descriptor =
 911                         ModuleDescriptor.newModule(mn, Set.of(SYNTHETIC))
 912                                         .packages(Set.of(pn, mn))
 913                                         .exports(mn)
 914                                         .build();
 915                 Module m = Modules.defineModule(ld, descriptor, null);
 916                 Modules.addReads(m, Proxy.class.getModule());
 917                 Modules.addExports(m, mn);
 918                 // java.base to create proxy instance and access its Lookup instance
 919                 Modules.addOpens(m, pn, Proxy.class.getModule());
 920                 Modules.addOpens(m, mn, Proxy.class.getModule());
 921                 return m;
 922             });
 923         }
 924     }
 925 
 926     /**
 927      * Returns a proxy instance for the specified interfaces
 928      * that dispatches method invocations to the specified invocation
 929      * handler.
 930      * <p>
 931      * <a id="restrictions">{@code IllegalArgumentException} will be thrown
 932      * if any of the following restrictions is violated:</a>
 933      * <ul>
 934      * <li>All of {@code Class} objects in the given {@code interfaces} array
 935      * must represent {@linkplain Class#isHidden() non-hidden} and
 936      * {@linkplain Class#isSealed() non-sealed} interfaces,
 937      * not classes or primitive types.
 938      *
 939      * <li>No two elements in the {@code interfaces} array may
 940      * refer to identical {@code Class} objects.
 941      *
 942      * <li>All of the interface types must be visible by name through the
 943      * specified class loader. In other words, for class loader
 944      * {@code cl} and every interface {@code i}, the following
 945      * expression must be true:<p>
 946      * {@code Class.forName(i.getName(), false, cl) == i}
 947      *
 948      * <li>All of the types referenced by all
 949      * public method signatures of the specified interfaces
 950      * and those inherited by their superinterfaces
 951      * must be visible by name through the specified class loader.
 952      *
 953      * <li>All non-public interfaces must be in the same package
 954      * and module, defined by the specified class loader and
 955      * the module of the non-public interfaces can access all of
 956      * the interface types; otherwise, it would not be possible for
 957      * the proxy class to implement all of the interfaces,
 958      * regardless of what package it is defined in.
 959      *
 960      * <li>For any set of member methods of the specified interfaces
 961      * that have the same signature:
 962      * <ul>
 963      * <li>If the return type of any of the methods is a primitive
 964      * type or void, then all of the methods must have that same
 965      * return type.
 966      * <li>Otherwise, one of the methods must have a return type that
 967      * is assignable to all of the return types of the rest of the
 968      * methods.
 969      * </ul>
 970      *
 971      * <li>The resulting proxy class must not exceed any limits imposed
 972      * on classes by the virtual machine.  For example, the VM may limit
 973      * the number of interfaces that a class may implement to 65535; in
 974      * that case, the size of the {@code interfaces} array must not
 975      * exceed 65535.
 976      * </ul>
 977      *
 978      * <p>Note that the order of the specified proxy interfaces is
 979      * significant: two requests for a proxy class with the same combination
 980      * of interfaces but in a different order will result in two distinct
 981      * proxy classes.
 982      *
 983      * @param   loader the class loader to define the proxy class
 984      * @param   interfaces the list of interfaces for the proxy class
 985      *          to implement
 986      * @param   h the invocation handler to dispatch method invocations to
 987      * @return  a proxy instance with the specified invocation handler of a
 988      *          proxy class that is defined by the specified class loader
 989      *          and that implements the specified interfaces
 990      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
 991      *          restrictions</a> on the parameters are violated
 992      * @throws  SecurityException if a security manager, <em>s</em>, is present
 993      *          and any of the following conditions is met:
 994      *          <ul>
 995      *          <li> the given {@code loader} is {@code null} and
 996      *               the caller's class loader is not {@code null} and the
 997      *               invocation of {@link SecurityManager#checkPermission
 998      *               s.checkPermission} with
 999      *               {@code RuntimePermission("getClassLoader")} permission
1000      *               denies access;</li>
1001      *          <li> for each proxy interface, {@code intf},
1002      *               the caller's class loader is not the same as or an
1003      *               ancestor of the class loader for {@code intf} and
1004      *               invocation of {@link SecurityManager#checkPackageAccess
1005      *               s.checkPackageAccess()} denies access to {@code intf};</li>
1006      *          <li> any of the given proxy interfaces is non-public and the
1007      *               caller class is not in the same {@linkplain Package runtime package}
1008      *               as the non-public interface and the invocation of
1009      *               {@link SecurityManager#checkPermission s.checkPermission} with
1010      *               {@code ReflectPermission("newProxyInPackage.{package name}")}
1011      *               permission denies access.</li>
1012      *          </ul>
1013      * @throws  NullPointerException if the {@code interfaces} array
1014      *          argument or any of its elements are {@code null}, or
1015      *          if the invocation handler, {@code h}, is
1016      *          {@code null}
1017      *
1018      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
1019      * @revised 9
1020      */
1021     @CallerSensitive
1022     public static Object newProxyInstance(ClassLoader loader,
1023                                           Class<?>[] interfaces,
1024                                           InvocationHandler h) {
1025         Objects.requireNonNull(h);
1026 
1027         @SuppressWarnings("removal")
1028         final Class<?> caller = System.getSecurityManager() == null
1029                                     ? null
1030                                     : Reflection.getCallerClass();
1031 
1032         /*
1033          * Look up or generate the designated proxy class and its constructor.
1034          */
1035         Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);
1036 
1037         return newProxyInstance(caller, cons, h);
1038     }
1039 
1040     private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager
1041                                            Constructor<?> cons,
1042                                            InvocationHandler h) {
1043         /*
1044          * Invoke its constructor with the designated invocation handler.
1045          */
1046         try {
1047             if (caller != null) {
1048                 checkNewProxyPermission(caller, cons.getDeclaringClass());
1049             }
1050 
1051             return cons.newInstance(new Object[]{h});
1052         } catch (IllegalAccessException | InstantiationException e) {
1053             throw new InternalError(e.toString(), e);
1054         } catch (InvocationTargetException e) {
1055             Throwable t = e.getCause();
1056             if (t instanceof RuntimeException re) {
1057                 throw re;
1058             } else {
1059                 throw new InternalError(t.toString(), t);
1060             }
1061         }
1062     }
1063 
1064     private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
1065         @SuppressWarnings("removal")
1066         SecurityManager sm = System.getSecurityManager();
1067         if (sm != null) {
1068             if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
1069                 ClassLoader ccl = caller.getClassLoader();
1070                 ClassLoader pcl = proxyClass.getClassLoader();
1071 
1072                 // do permission check if the caller is in a different runtime package
1073                 // of the proxy class
1074                 String pkg = proxyClass.getPackageName();
1075                 String callerPkg = caller.getPackageName();
1076 
1077                 if (pcl != ccl || !pkg.equals(callerPkg)) {
1078                     sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
1079                 }
1080             }
1081         }
1082     }
1083 
1084     /**
1085      * Returns the class loader for the given module.
1086      */
1087     @SuppressWarnings("removal")
1088     private static ClassLoader getLoader(Module m) {
1089         PrivilegedAction<ClassLoader> pa = m::getClassLoader;
1090         return AccessController.doPrivileged(pa);
1091     }
1092 
1093     /**
1094      * Returns true if the given class is a proxy class.
1095      *
1096      * @implNote The reliability of this method is important for the ability
1097      * to use it to make security decisions, so its implementation should
1098      * not just test if the class in question extends {@code Proxy}.
1099      *
1100      * @param   cl the class to test
1101      * @return  {@code true} if the class is a proxy class and
1102      *          {@code false} otherwise
1103      * @throws  NullPointerException if {@code cl} is {@code null}
1104      *
1105      * @revised 9
1106      */
1107     public static boolean isProxyClass(Class<?> cl) {
1108         return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl);
1109     }
1110 
1111     /**
1112      * Returns the invocation handler for the specified proxy instance.
1113      *
1114      * @param   proxy the proxy instance to return the invocation handler for
1115      * @return  the invocation handler for the proxy instance
1116      * @throws  IllegalArgumentException if the argument is not a
1117      *          proxy instance
1118      * @throws  SecurityException if a security manager, <em>s</em>, is present
1119      *          and the caller's class loader is not the same as or an
1120      *          ancestor of the class loader for the invocation handler
1121      *          and invocation of {@link SecurityManager#checkPackageAccess
1122      *          s.checkPackageAccess()} denies access to the invocation
1123      *          handler's class.
1124      */
1125     @SuppressWarnings("removal")
1126     @CallerSensitive
1127     public static InvocationHandler getInvocationHandler(Object proxy)
1128         throws IllegalArgumentException
1129     {
1130         /*
1131          * Verify that the object is actually a proxy instance.
1132          */
1133         if (!isProxyClass(proxy.getClass())) {
1134             throw new IllegalArgumentException("not a proxy instance");
1135         }
1136 
1137         final Proxy p = (Proxy) proxy;
1138         final InvocationHandler ih = p.h;
1139         if (System.getSecurityManager() != null) {
1140             Class<?> ihClass = ih.getClass();
1141             Class<?> caller = Reflection.getCallerClass();
1142             if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
1143                                                     ihClass.getClassLoader()))
1144             {
1145                 ReflectUtil.checkPackageAccess(ihClass);
1146             }
1147         }
1148 
1149         return ih;
1150     }
1151 
1152     private static final String PROXY_PACKAGE_PREFIX = ReflectUtil.PROXY_PACKAGE;
1153 
1154     /**
1155      * A cache of Method -> MethodHandle for default methods.
1156      */
1157     private static final ClassValue<ConcurrentHashMap<Method, MethodHandle>>
1158             DEFAULT_METHODS_MAP = new ClassValue<>() {
1159         @Override
1160         protected ConcurrentHashMap<Method, MethodHandle> computeValue(Class<?> type) {
1161             return new ConcurrentHashMap<>(4);
1162         }
1163     };
1164 
1165     private static ConcurrentHashMap<Method, MethodHandle> defaultMethodMap(Class<?> proxyClass) {
1166         assert isProxyClass(proxyClass);
1167         return DEFAULT_METHODS_MAP.get(proxyClass);
1168     }
1169 
1170     static final Object[] EMPTY_ARGS = new Object[0];
1171 
1172     static MethodHandle defaultMethodHandle(Class<? extends Proxy> proxyClass, Method method) {
1173         // lookup the cached method handle
1174         ConcurrentHashMap<Method, MethodHandle> methods = defaultMethodMap(proxyClass);
1175         MethodHandle superMH = methods.get(method);
1176         if (superMH == null) {
1177             MethodType type = methodType(method.getReturnType(), method.getParameterTypes());
1178             MethodHandles.Lookup lookup = MethodHandles.lookup();
1179             Class<?> proxyInterface = findProxyInterfaceOrElseThrow(proxyClass, method);
1180             MethodHandle dmh;
1181             try {
1182                 dmh = proxyClassLookup(lookup, proxyClass)
1183                         .findSpecial(proxyInterface, method.getName(), type, proxyClass)
1184                         .withVarargs(false);
1185             } catch (IllegalAccessException | NoSuchMethodException e) {
1186                 // should not reach here
1187                 throw new InternalError(e);
1188             }
1189             // this check can be turned into assertion as it is guaranteed to succeed by the virtue of
1190             // looking up a default (instance) method declared or inherited by proxyInterface
1191             // while proxyClass implements (is a subtype of) proxyInterface ...
1192             assert ((BooleanSupplier) () -> {
1193                 try {
1194                     // make sure that the method type matches
1195                     dmh.asType(type.insertParameterTypes(0, proxyClass));
1196                     return true;
1197                 } catch (WrongMethodTypeException e) {
1198                     return false;
1199                 }
1200             }).getAsBoolean() : "Wrong method type";
1201             // change return type to Object
1202             MethodHandle mh = dmh.asType(dmh.type().changeReturnType(Object.class));
1203             // wrap any exception thrown with InvocationTargetException
1204             mh = MethodHandles.catchException(mh, Throwable.class, InvocationException.wrapMH());
1205             // spread array of arguments among parameters (skipping 1st parameter - target)
1206             mh = mh.asSpreader(1, Object[].class, type.parameterCount());
1207             // change target type to Object
1208             mh = mh.asType(MethodType.methodType(Object.class, Object.class, Object[].class));
1209 
1210             // push MH into cache
1211             MethodHandle cached = methods.putIfAbsent(method, mh);
1212             if (cached != null) {
1213                 superMH = cached;
1214             } else {
1215                 superMH = mh;
1216             }
1217         }
1218         return superMH;
1219     }
1220 
1221     /**
1222      * Finds the first proxy interface that declares the given method
1223      * directly or indirectly.
1224      *
1225      * @throws IllegalArgumentException if not found
1226      */
1227     private static Class<?> findProxyInterfaceOrElseThrow(Class<?> proxyClass, Method method) {
1228         Class<?> declaringClass = method.getDeclaringClass();
1229         if (!declaringClass.isInterface()) {
1230             throw new IllegalArgumentException("\"" + method +
1231                     "\" is not a method declared in the proxy class");
1232         }
1233 
1234         List<Class<?>> proxyInterfaces = Arrays.asList(proxyClass.getInterfaces());
1235         // the method's declaring class is a proxy interface
1236         if (proxyInterfaces.contains(declaringClass))
1237             return declaringClass;
1238 
1239         // find the first proxy interface that inherits the default method
1240         // i.e. the declaring class of the default method is a superinterface
1241         // of the proxy interface
1242         Deque<Class<?>> deque = new ArrayDeque<>();
1243         Set<Class<?>> visited = new HashSet<>();
1244         boolean indirectMethodRef = false;
1245         for (Class<?> proxyIntf : proxyInterfaces) {
1246             assert proxyIntf != declaringClass;
1247             visited.add(proxyIntf);
1248             deque.add(proxyIntf);
1249 
1250             // for each proxy interface, traverse its subinterfaces with
1251             // breadth-first search to find a subinterface declaring the
1252             // default method
1253             Class<?> c;
1254             while ((c = deque.poll()) != null) {
1255                 if (c == declaringClass) {
1256                     try {
1257                         // check if this method is the resolved method if referenced from
1258                         // this proxy interface (i.e. this method is not implemented
1259                         // by any other superinterface)
1260                         Method m = proxyIntf.getMethod(method.getName(), method.getSharedParameterTypes());
1261                         if (m.getDeclaringClass() == declaringClass) {
1262                             return proxyIntf;
1263                         }
1264                         indirectMethodRef = true;
1265                     } catch (NoSuchMethodException e) {}
1266 
1267                     // skip traversing its superinterfaces
1268                     // another proxy interface may extend it and so
1269                     // the method's declaring class is left unvisited.
1270                     continue;
1271                 }
1272                 // visit all superinterfaces of one proxy interface to find if
1273                 // this proxy interface inherits the method directly or indirectly
1274                 visited.add(c);
1275                 for (Class<?> superIntf : c.getInterfaces()) {
1276                     if (!visited.contains(superIntf) && !deque.contains(superIntf)) {
1277                         if (superIntf == declaringClass) {
1278                             // fast-path as the matching subinterface is found
1279                             deque.addFirst(superIntf);
1280                         } else {
1281                             deque.add(superIntf);
1282                         }
1283                     }
1284                 }
1285             }
1286         }
1287 
1288         throw new IllegalArgumentException("\"" + method + (indirectMethodRef
1289                 ? "\" is overridden directly or indirectly by the proxy interfaces"
1290                 : "\" is not a method declared in the proxy class"));
1291     }
1292 
1293     /**
1294      * This method invokes the proxy's proxyClassLookup method to get a
1295      * Lookup on the proxy class.
1296      *
1297      * @return a lookup for proxy class of this proxy instance
1298      */
1299     @SuppressWarnings("removal")
1300     private static MethodHandles.Lookup proxyClassLookup(MethodHandles.Lookup caller, Class<?> proxyClass) {
1301         return AccessController.doPrivileged(new PrivilegedAction<>() {
1302             @Override
1303             public MethodHandles.Lookup run() {
1304                 try {
1305                     Method m = proxyClass.getDeclaredMethod("proxyClassLookup", MethodHandles.Lookup.class);
1306                     m.setAccessible(true);
1307                     return (MethodHandles.Lookup) m.invoke(null, caller);
1308                 } catch (ReflectiveOperationException e) {
1309                     throw new InternalError(e);
1310                 }
1311             }
1312         });
1313     }
1314 
1315     /*
1316      * Invoke the default method of the given proxy with an explicit caller class.
1317      *
1318      * @throws IllegalAccessException if the proxy interface is inaccessible to the caller
1319      *         if caller is non-null
1320      */
1321     static Object invokeDefault(Object proxy, Method method, Object[] args, Class<?> caller)
1322             throws Throwable {
1323         // verify that the object is actually a proxy instance
1324         if (!Proxy.isProxyClass(proxy.getClass())) {
1325             throw new IllegalArgumentException("'proxy' is not a proxy instance");
1326         }
1327         if (!method.isDefault()) {
1328             throw new IllegalArgumentException("\"" + method + "\" is not a default method");
1329         }
1330         @SuppressWarnings("unchecked")
1331         Class<? extends Proxy> proxyClass = (Class<? extends Proxy>)proxy.getClass();
1332 
1333         // skip access check if caller is null
1334         if (caller != null) {
1335             Class<?> intf = method.getDeclaringClass();
1336             // access check on the default method
1337             method.checkAccess(caller, intf, proxyClass, method.getModifiers());
1338         }
1339 
1340         MethodHandle mh = Proxy.defaultMethodHandle(proxyClass, method);
1341         // invoke the super method
1342         try {
1343             // the args array can be null if the number of formal parameters required by
1344             // the method is zero (consistent with Method::invoke)
1345             Object[] params = args != null ? args : Proxy.EMPTY_ARGS;
1346             return mh.invokeExact(proxy, params);
1347         } catch (ClassCastException | NullPointerException e) {
1348             throw new IllegalArgumentException(e.getMessage(), e);
1349         } catch (Proxy.InvocationException e) {
1350             // unwrap and throw the exception thrown by the default method
1351             throw e.getCause();
1352         }
1353     }
1354 
1355     /**
1356      * Internal exception type to wrap the exception thrown by the default method
1357      * so that it can distinguish CCE and NPE thrown due to the arguments
1358      * incompatible with the method signature.
1359      */
1360     static class InvocationException extends ReflectiveOperationException {
1361         @java.io.Serial
1362         private static final long serialVersionUID = 0L;
1363 
1364         InvocationException(Throwable cause) {
1365             super(cause);
1366         }
1367 
1368         /**
1369          * Wraps given cause with InvocationException and throws it.
1370          */
1371         static Object wrap(Throwable cause) throws InvocationException {
1372             throw new InvocationException(cause);
1373         }
1374 
1375         @Stable
1376         static MethodHandle wrapMethodHandle;
1377 
1378         static MethodHandle wrapMH() {
1379             MethodHandle mh = wrapMethodHandle;
1380             if (mh == null) {
1381                 try {
1382                     wrapMethodHandle = mh = MethodHandles.lookup().findStatic(
1383                             InvocationException.class,
1384                             "wrap",
1385                             MethodType.methodType(Object.class, Throwable.class)
1386                     );
1387                 } catch (NoSuchMethodException | IllegalAccessException e) {
1388                     throw new InternalError(e);
1389                 }
1390             }
1391             return mh;
1392         }
1393     }
1394 
1395 }