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