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             if (target == m) return;
 860 
 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 (type != 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      */
1020     @CallerSensitive
1021     public static Object newProxyInstance(ClassLoader loader,
1022                                           Class<?>[] interfaces,
1023                                           InvocationHandler h) {
1024         Objects.requireNonNull(h);
1025 
1026         @SuppressWarnings("removal")
1027         final Class<?> caller = System.getSecurityManager() == null
1028                                     ? null
1029                                     : Reflection.getCallerClass();
1030 
1031         /*
1032          * Look up or generate the designated proxy class and its constructor.
1033          */
1034         Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);
1035 
1036         return newProxyInstance(caller, cons, h);
1037     }
1038 
1039     private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager
1040                                            Constructor<?> cons,
1041                                            InvocationHandler h) {
1042         /*
1043          * Invoke its constructor with the designated invocation handler.
1044          */
1045         try {
1046             if (caller != null) {
1047                 checkNewProxyPermission(caller, cons.getDeclaringClass());
1048             }
1049 
1050             return cons.newInstance(new Object[]{h});
1051         } catch (IllegalAccessException | InstantiationException e) {
1052             throw new InternalError(e.toString(), e);
1053         } catch (InvocationTargetException e) {
1054             Throwable t = e.getCause();
1055             if (t instanceof RuntimeException re) {
1056                 throw re;
1057             } else {
1058                 throw new InternalError(t.toString(), t);
1059             }
1060         }
1061     }
1062 
1063     private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
1064         @SuppressWarnings("removal")
1065         SecurityManager sm = System.getSecurityManager();
1066         if (sm != null) {
1067             if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
1068                 ClassLoader ccl = caller.getClassLoader();
1069                 ClassLoader pcl = proxyClass.getClassLoader();
1070 
1071                 // do permission check if the caller is in a different runtime package
1072                 // of the proxy class
1073                 String pkg = proxyClass.getPackageName();
1074                 String callerPkg = caller.getPackageName();
1075 
1076                 if (pcl != ccl || !pkg.equals(callerPkg)) {
1077                     sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
1078                 }
1079             }
1080         }
1081     }
1082 
1083     /**
1084      * Returns the class loader for the given module.
1085      */
1086     @SuppressWarnings("removal")
1087     private static ClassLoader getLoader(Module m) {
1088         PrivilegedAction<ClassLoader> pa = m::getClassLoader;
1089         return AccessController.doPrivileged(pa);
1090     }
1091 
1092     /**
1093      * Returns true if the given class is a proxy class.
1094      *
1095      * @implNote The reliability of this method is important for the ability
1096      * to use it to make security decisions, so its implementation should
1097      * not just test if the class in question extends {@code Proxy}.
1098      *
1099      * @param   cl the class to test
1100      * @return  {@code true} if the class is a proxy class and
1101      *          {@code false} otherwise
1102      * @throws  NullPointerException if {@code cl} is {@code null}
1103      */
1104     public static boolean isProxyClass(Class<?> cl) {
1105         return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl);
1106     }
1107 
1108     /**
1109      * Returns the invocation handler for the specified proxy instance.
1110      *
1111      * @param   proxy the proxy instance to return the invocation handler for
1112      * @return  the invocation handler for the proxy instance
1113      * @throws  IllegalArgumentException if the argument is not a
1114      *          proxy instance
1115      * @throws  SecurityException if a security manager, <em>s</em>, is present
1116      *          and the caller's class loader is not the same as or an
1117      *          ancestor of the class loader for the invocation handler
1118      *          and invocation of {@link SecurityManager#checkPackageAccess
1119      *          s.checkPackageAccess()} denies access to the invocation
1120      *          handler's class.
1121      */
1122     @SuppressWarnings("removal")
1123     @CallerSensitive
1124     public static InvocationHandler getInvocationHandler(Object proxy)
1125         throws IllegalArgumentException
1126     {
1127         /*
1128          * Verify that the object is actually a proxy instance.
1129          */
1130         if (!isProxyClass(proxy.getClass())) {
1131             throw new IllegalArgumentException("not a proxy instance");
1132         }
1133 
1134         final Proxy p = (Proxy) proxy;
1135         final InvocationHandler ih = p.h;
1136         if (System.getSecurityManager() != null) {
1137             Class<?> ihClass = ih.getClass();
1138             Class<?> caller = Reflection.getCallerClass();
1139             if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
1140                                                     ihClass.getClassLoader()))
1141             {
1142                 ReflectUtil.checkPackageAccess(ihClass);
1143             }
1144         }
1145 
1146         return ih;
1147     }
1148 
1149     private static final String PROXY_PACKAGE_PREFIX = ReflectUtil.PROXY_PACKAGE;
1150 
1151     /**
1152      * A cache of Method -> MethodHandle for default methods.
1153      */
1154     private static final ClassValue<ConcurrentHashMap<Method, MethodHandle>>
1155             DEFAULT_METHODS_MAP = new ClassValue<>() {
1156         @Override
1157         protected ConcurrentHashMap<Method, MethodHandle> computeValue(Class<?> type) {
1158             return new ConcurrentHashMap<>(4);
1159         }
1160     };
1161 
1162     private static ConcurrentHashMap<Method, MethodHandle> defaultMethodMap(Class<?> proxyClass) {
1163         assert isProxyClass(proxyClass);
1164         return DEFAULT_METHODS_MAP.get(proxyClass);
1165     }
1166 
1167     static final Object[] EMPTY_ARGS = new Object[0];
1168 
1169     static MethodHandle defaultMethodHandle(Class<? extends Proxy> proxyClass, Method method) {
1170         // lookup the cached method handle
1171         ConcurrentHashMap<Method, MethodHandle> methods = defaultMethodMap(proxyClass);
1172         MethodHandle superMH = methods.get(method);
1173         if (superMH == null) {
1174             MethodType type = methodType(method.getReturnType(), method.getParameterTypes());
1175             MethodHandles.Lookup lookup = MethodHandles.lookup();
1176             Class<?> proxyInterface = findProxyInterfaceOrElseThrow(proxyClass, method);
1177             MethodHandle dmh;
1178             try {
1179                 dmh = proxyClassLookup(lookup, proxyClass)
1180                         .findSpecial(proxyInterface, method.getName(), type, proxyClass)
1181                         .withVarargs(false);
1182             } catch (IllegalAccessException | NoSuchMethodException e) {
1183                 // should not reach here
1184                 throw new InternalError(e);
1185             }
1186             // this check can be turned into assertion as it is guaranteed to succeed by the virtue of
1187             // looking up a default (instance) method declared or inherited by proxyInterface
1188             // while proxyClass implements (is a subtype of) proxyInterface ...
1189             assert ((BooleanSupplier) () -> {
1190                 try {
1191                     // make sure that the method type matches
1192                     dmh.asType(type.insertParameterTypes(0, proxyClass));
1193                     return true;
1194                 } catch (WrongMethodTypeException e) {
1195                     return false;
1196                 }
1197             }).getAsBoolean() : "Wrong method type";
1198             // change return type to Object
1199             MethodHandle mh = dmh.asType(dmh.type().changeReturnType(Object.class));
1200             // wrap any exception thrown with InvocationTargetException
1201             mh = MethodHandles.catchException(mh, Throwable.class, InvocationException.wrapMH());
1202             // spread array of arguments among parameters (skipping 1st parameter - target)
1203             mh = mh.asSpreader(1, Object[].class, type.parameterCount());
1204             // change target type to Object
1205             mh = mh.asType(MethodType.methodType(Object.class, Object.class, Object[].class));
1206 
1207             // push MH into cache
1208             MethodHandle cached = methods.putIfAbsent(method, mh);
1209             if (cached != null) {
1210                 superMH = cached;
1211             } else {
1212                 superMH = mh;
1213             }
1214         }
1215         return superMH;
1216     }
1217 
1218     /**
1219      * Finds the first proxy interface that declares the given method
1220      * directly or indirectly.
1221      *
1222      * @throws IllegalArgumentException if not found
1223      */
1224     private static Class<?> findProxyInterfaceOrElseThrow(Class<?> proxyClass, Method method) {
1225         Class<?> declaringClass = method.getDeclaringClass();
1226         if (!declaringClass.isInterface()) {
1227             throw new IllegalArgumentException("\"" + method +
1228                     "\" is not a method declared in the proxy class");
1229         }
1230 
1231         List<Class<?>> proxyInterfaces = Arrays.asList(proxyClass.getInterfaces());
1232         // the method's declaring class is a proxy interface
1233         if (proxyInterfaces.contains(declaringClass))
1234             return declaringClass;
1235 
1236         // find the first proxy interface that inherits the default method
1237         // i.e. the declaring class of the default method is a superinterface
1238         // of the proxy interface
1239         Deque<Class<?>> deque = new ArrayDeque<>();
1240         Set<Class<?>> visited = new HashSet<>();
1241         boolean indirectMethodRef = false;
1242         for (Class<?> proxyIntf : proxyInterfaces) {
1243             assert proxyIntf != declaringClass;
1244             visited.add(proxyIntf);
1245             deque.add(proxyIntf);
1246 
1247             // for each proxy interface, traverse its subinterfaces with
1248             // breadth-first search to find a subinterface declaring the
1249             // default method
1250             Class<?> c;
1251             while ((c = deque.poll()) != null) {
1252                 if (c == declaringClass) {
1253                     try {
1254                         // check if this method is the resolved method if referenced from
1255                         // this proxy interface (i.e. this method is not implemented
1256                         // by any other superinterface)
1257                         Method m = proxyIntf.getMethod(method.getName(), method.getSharedParameterTypes());
1258                         if (m.getDeclaringClass() == declaringClass) {
1259                             return proxyIntf;
1260                         }
1261                         indirectMethodRef = true;
1262                     } catch (NoSuchMethodException e) {}
1263 
1264                     // skip traversing its superinterfaces
1265                     // another proxy interface may extend it and so
1266                     // the method's declaring class is left unvisited.
1267                     continue;
1268                 }
1269                 // visit all superinterfaces of one proxy interface to find if
1270                 // this proxy interface inherits the method directly or indirectly
1271                 visited.add(c);
1272                 for (Class<?> superIntf : c.getInterfaces()) {
1273                     if (!visited.contains(superIntf) && !deque.contains(superIntf)) {
1274                         if (superIntf == declaringClass) {
1275                             // fast-path as the matching subinterface is found
1276                             deque.addFirst(superIntf);
1277                         } else {
1278                             deque.add(superIntf);
1279                         }
1280                     }
1281                 }
1282             }
1283         }
1284 
1285         throw new IllegalArgumentException("\"" + method + (indirectMethodRef
1286                 ? "\" is overridden directly or indirectly by the proxy interfaces"
1287                 : "\" is not a method declared in the proxy class"));
1288     }
1289 
1290     /**
1291      * This method invokes the proxy's proxyClassLookup method to get a
1292      * Lookup on the proxy class.
1293      *
1294      * @return a lookup for proxy class of this proxy instance
1295      */
1296     @SuppressWarnings("removal")
1297     private static MethodHandles.Lookup proxyClassLookup(MethodHandles.Lookup caller, Class<?> proxyClass) {
1298         return AccessController.doPrivileged(new PrivilegedAction<>() {
1299             @Override
1300             public MethodHandles.Lookup run() {
1301                 try {
1302                     Method m = proxyClass.getDeclaredMethod("proxyClassLookup", MethodHandles.Lookup.class);
1303                     m.setAccessible(true);
1304                     return (MethodHandles.Lookup) m.invoke(null, caller);
1305                 } catch (ReflectiveOperationException e) {
1306                     throw new InternalError(e);
1307                 }
1308             }
1309         });
1310     }
1311 
1312     /*
1313      * Invoke the default method of the given proxy with an explicit caller class.
1314      *
1315      * @throws IllegalAccessException if the proxy interface is inaccessible to the caller
1316      *         if caller is non-null
1317      */
1318     static Object invokeDefault(Object proxy, Method method, Object[] args, Class<?> caller)
1319             throws Throwable {
1320         // verify that the object is actually a proxy instance
1321         if (!Proxy.isProxyClass(proxy.getClass())) {
1322             throw new IllegalArgumentException("'proxy' is not a proxy instance");
1323         }
1324         if (!method.isDefault()) {
1325             throw new IllegalArgumentException("\"" + method + "\" is not a default method");
1326         }
1327         @SuppressWarnings("unchecked")
1328         Class<? extends Proxy> proxyClass = (Class<? extends Proxy>)proxy.getClass();
1329 
1330         // skip access check if caller is null
1331         if (caller != null) {
1332             Class<?> intf = method.getDeclaringClass();
1333             // access check on the default method
1334             method.checkAccess(caller, intf, proxyClass, method.getModifiers());
1335         }
1336 
1337         MethodHandle mh = Proxy.defaultMethodHandle(proxyClass, method);
1338         // invoke the super method
1339         try {
1340             // the args array can be null if the number of formal parameters required by
1341             // the method is zero (consistent with Method::invoke)
1342             Object[] params = args != null ? args : Proxy.EMPTY_ARGS;
1343             return mh.invokeExact(proxy, params);
1344         } catch (ClassCastException | NullPointerException e) {
1345             throw new IllegalArgumentException(e.getMessage(), e);
1346         } catch (Proxy.InvocationException e) {
1347             // unwrap and throw the exception thrown by the default method
1348             throw e.getCause();
1349         }
1350     }
1351 
1352     /**
1353      * Internal exception type to wrap the exception thrown by the default method
1354      * so that it can distinguish CCE and NPE thrown due to the arguments
1355      * incompatible with the method signature.
1356      */
1357     static class InvocationException extends ReflectiveOperationException {
1358         @java.io.Serial
1359         private static final long serialVersionUID = 0L;
1360 
1361         InvocationException(Throwable cause) {
1362             super(cause);
1363         }
1364 
1365         /**
1366          * Wraps given cause with InvocationException and throws it.
1367          */
1368         static Object wrap(Throwable cause) throws InvocationException {
1369             throw new InvocationException(cause);
1370         }
1371 
1372         @Stable
1373         static MethodHandle wrapMethodHandle;
1374 
1375         static MethodHandle wrapMH() {
1376             MethodHandle mh = wrapMethodHandle;
1377             if (mh == null) {
1378                 try {
1379                     wrapMethodHandle = mh = MethodHandles.lookup().findStatic(
1380                             InvocationException.class,
1381                             "wrap",
1382                             MethodType.methodType(Object.class, Throwable.class)
1383                     );
1384                 } catch (NoSuchMethodException | IllegalAccessException e) {
1385                     throw new InternalError(e);
1386                 }
1387             }
1388             return mh;
1389         }
1390     }
1391 
1392 }