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 | Modifier.IDENTITY)) != 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 | Modifier.IDENTITY);
 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             if (!VM.isModuleSystemInited()) {
 622                 throw new InternalError("Proxy is not supported until "
 623                         + "module system is fully initialized");
 624             }
 625             if (interfaces.size() > 65535) {
 626                 throw new IllegalArgumentException("interface limit exceeded: "
 627                         + interfaces.size());
 628             }
 629 
 630             Set<Class<?>> refTypes = referencedTypes(loader, interfaces);
 631 
 632             // IAE if violates any restrictions specified in newProxyInstance
 633             validateProxyInterfaces(loader, interfaces, refTypes);
 634 
 635             this.interfaces = interfaces;
 636             this.context = proxyClassContext(loader, interfaces, refTypes);
 637             assert getLoader(context.module()) == loader;
 638         }
 639 
 640         ProxyBuilder(ClassLoader loader, Class<?> intf) {
 641             this(loader, Collections.singletonList(intf));
 642         }
 643 
 644         /**
 645          * Generate a proxy class and return its proxy Constructor with
 646          * accessible flag already set. If the target module does not have access
 647          * to any interface types, IllegalAccessError will be thrown by the VM
 648          * at defineClass time.
 649          *
 650          * Must call the checkProxyAccess method to perform permission checks
 651          * before calling this.
 652          */
 653         @SuppressWarnings("removal")
 654         Constructor<?> build() {
 655             Class<?> proxyClass = defineProxyClass(context, interfaces);
 656 
 657             final Constructor<?> cons;
 658             try {
 659                 cons = proxyClass.getConstructor(constructorParams);
 660             } catch (NoSuchMethodException e) {
 661                 throw new InternalError(e.toString(), e);
 662             }
 663             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 664                 public Void run() {
 665                     cons.setAccessible(true);
 666                     return null;
 667                 }
 668             });
 669             return cons;
 670         }
 671 
 672         /**
 673          * Validate the given proxy interfaces and the given referenced types
 674          * are visible to the defining loader.
 675          *
 676          * @throws IllegalArgumentException if it violates the restrictions
 677          *         specified in {@link Proxy#newProxyInstance}
 678          */
 679         private static void validateProxyInterfaces(ClassLoader loader,
 680                                                     List<Class<?>> interfaces,
 681                                                     Set<Class<?>> refTypes)
 682         {
 683             Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.size());
 684             for (Class<?> intf : interfaces) {
 685                 /*
 686                  * Verify that the Class object actually represents an
 687                  * interface.
 688                  */
 689                 if (!intf.isInterface()) {
 690                     throw new IllegalArgumentException(intf.getName() + " is not an interface");
 691                 }
 692 
 693                 if (intf.isHidden()) {
 694                     throw new IllegalArgumentException(intf.getName() + " is a hidden interface");
 695                 }
 696 
 697                 if (intf.isSealed()) {
 698                     throw new IllegalArgumentException(intf.getName() + " is a sealed interface");
 699                 }
 700 
 701                 /*
 702                  * Verify that the class loader resolves the name of this
 703                  * interface to the same Class object.
 704                  */
 705                 ensureVisible(loader, intf);
 706 
 707                 /*
 708                  * Verify that this interface is not a duplicate.
 709                  */
 710                 if (interfaceSet.put(intf, Boolean.TRUE) != null) {
 711                     throw new IllegalArgumentException("repeated interface: " + intf.getName());
 712                 }
 713             }
 714 
 715             for (Class<?> type : refTypes) {
 716                 ensureVisible(loader, type);
 717             }
 718         }
 719 
 720         /*
 721          * Returns all types referenced by all public non-static method signatures of
 722          * the proxy interfaces
 723          */
 724         private static Set<Class<?>> referencedTypes(ClassLoader loader,
 725                                                      List<Class<?>> interfaces) {
 726             var types = new HashSet<Class<?>>();
 727             for (var intf : interfaces) {
 728                 for (Method m : intf.getMethods()) {
 729                     if (!Modifier.isStatic(m.getModifiers())) {
 730                         addElementType(types, m.getReturnType());
 731                         addElementTypes(types, m.getSharedParameterTypes());
 732                         addElementTypes(types, m.getSharedExceptionTypes());
 733                     }
 734                 }
 735             }
 736             return types;
 737         }
 738 
 739         private static void addElementTypes(HashSet<Class<?>> types,
 740                                             Class<?> ... classes) {
 741             for (var cls : classes) {
 742                 addElementType(types, cls);
 743             }
 744         }
 745 
 746         private static void addElementType(HashSet<Class<?>> types,
 747                                            Class<?> cls) {
 748             var type = getElementType(cls);
 749             if (!type.isPrimitive()) {
 750                 types.add(type);
 751             }
 752         }
 753 
 754         /**
 755          * Returns the context for the generated proxy class, including the
 756          * module and the package it belongs to and whether it is package-private.
 757          *
 758          * If any of proxy interface is package-private, then the proxy class
 759          * is in the same package and module as the package-private interface.
 760          *
 761          * If all proxy interfaces are public and in exported packages,
 762          * then the proxy class is in a dynamic module in an unconditionally
 763          * exported package.
 764          *
 765          * If all proxy interfaces are public and at least one in a non-exported
 766          * package, then the proxy class is in a dynamic module in a
 767          * non-exported package.
 768          *
 769          * The package of proxy class is open to java.base for deep reflective access.
 770          *
 771          * Reads edge and qualified exports are added for dynamic module to access.
 772          */
 773         private static ProxyClassContext proxyClassContext(ClassLoader loader,
 774                                                            List<Class<?>> interfaces,
 775                                                            Set<Class<?>> refTypes) {
 776             Map<Class<?>, Module> packagePrivateTypes = new HashMap<>();
 777             boolean nonExported = false;
 778 
 779             for (Class<?> intf : interfaces) {
 780                 Module m = intf.getModule();
 781                 if (!Modifier.isPublic(intf.getModifiers())) {
 782                     packagePrivateTypes.put(intf, m);
 783                 } else {
 784                     if (!intf.getModule().isExported(intf.getPackageName())) {
 785                         // module-private types
 786                         nonExported = true;
 787                     }
 788                 }
 789             }
 790 
 791             if (packagePrivateTypes.size() > 0) {
 792                 // all package-private types must be in the same runtime package
 793                 // i.e. same package name and same module (named or unnamed)
 794                 //
 795                 // Configuration will fail if M1 and in M2 defined by the same loader
 796                 // and both have the same package p (so no need to check class loader)
 797                 Module targetModule = null;
 798                 String targetPackageName = null;
 799                 for (Map.Entry<Class<?>, Module> e : packagePrivateTypes.entrySet()) {
 800                     Class<?> intf = e.getKey();
 801                     Module m = e.getValue();
 802                     if ((targetModule != null && targetModule != m) ||
 803                         (targetPackageName != null && targetPackageName != intf.getPackageName())) {
 804                         throw new IllegalArgumentException(
 805                                 "cannot have non-public interfaces in different packages");
 806                     }
 807                     if (getLoader(m) != loader) {
 808                         // the specified loader is not the same class loader
 809                         // of the non-public interface
 810                         throw new IllegalArgumentException(
 811                                 "non-public interface is not defined by the given loader");
 812                     }
 813 
 814                     targetModule = m;
 815                     targetPackageName = e.getKey().getPackageName();
 816                 }
 817 
 818                 // validate if the target module can access all other interfaces
 819                 for (Class<?> intf : interfaces) {
 820                     Module m = intf.getModule();
 821                     if (m == targetModule) continue;
 822 
 823                     if (!targetModule.canRead(m) || !m.isExported(intf.getPackageName(), targetModule)) {
 824                         throw new IllegalArgumentException(targetModule + " can't access " + intf.getName());
 825                     }
 826                 }
 827 
 828                 // opens the package of the non-public proxy class for java.base to access
 829                 if (targetModule.isNamed()) {
 830                     Modules.addOpens(targetModule, targetPackageName, Proxy.class.getModule());
 831                 }
 832                 // return the module of the package-private interface
 833                 return new ProxyClassContext(targetModule, targetPackageName, 0);
 834             }
 835 
 836             // All proxy interfaces are public.  So maps to a dynamic proxy module
 837             // and add reads edge and qualified exports, if necessary
 838             Module targetModule = getDynamicModule(loader);
 839 
 840             // set up proxy class access to proxy interfaces and types
 841             // referenced in the method signature
 842             Set<Class<?>> types = new HashSet<>(interfaces);
 843             types.addAll(refTypes);
 844             for (Class<?> c : types) {
 845                 ensureAccess(targetModule, c);
 846             }
 847 
 848             var pkgName = nonExported ? PROXY_PACKAGE_PREFIX + '.' + targetModule.getName()
 849                                       : targetModule.getName();
 850             return new ProxyClassContext(targetModule, pkgName, Modifier.PUBLIC);
 851         }
 852 
 853         /*
 854          * Ensure the given module can access the given class.
 855          */
 856         private static void ensureAccess(Module target, Class<?> c) {
 857             Module m = c.getModule();
 858             // add read edge and qualified export for the target module to access
 859             if (!target.canRead(m)) {
 860                 Modules.addReads(target, m);
 861             }
 862             String pn = c.getPackageName();
 863             if (!m.isExported(pn, target)) {
 864                 Modules.addExports(m, pn, target);
 865             }
 866         }
 867 
 868         /*
 869          * Ensure the given class is visible to the class loader.
 870          */
 871         private static void ensureVisible(ClassLoader ld, Class<?> c) {
 872             Class<?> type = null;
 873             try {
 874                 type = Class.forName(c.getName(), false, ld);
 875             } catch (ClassNotFoundException e) {
 876             }
 877             if (type != c) {
 878                 throw new IllegalArgumentException(c.getName() +
 879                         " referenced from a method is not visible from class loader: " + JLA.getLoaderNameID(ld));
 880             }
 881         }
 882 
 883         private static Class<?> getElementType(Class<?> type) {
 884             Class<?> e = type;
 885             while (e.isArray()) {
 886                 e = e.getComponentType();
 887             }
 888             return e;
 889         }
 890 
 891         private static final ClassLoaderValue<Module> dynProxyModules =
 892             new ClassLoaderValue<>();
 893         private static final AtomicInteger counter = new AtomicInteger();
 894 
 895         /*
 896          * Define a dynamic module with a package named $MODULE which
 897          * is unconditionally exported and another package named
 898          * com.sun.proxy.$MODULE which is encapsulated.
 899          *
 900          * Each class loader will have one dynamic module.
 901          */
 902         private static Module getDynamicModule(ClassLoader loader) {
 903             return dynProxyModules.computeIfAbsent(loader, (ld, clv) -> {
 904                 // create a dynamic module and setup module access
 905                 String mn = "jdk.proxy" + counter.incrementAndGet();
 906                 String pn = PROXY_PACKAGE_PREFIX + "." + mn;
 907                 ModuleDescriptor descriptor =
 908                         ModuleDescriptor.newModule(mn, Set.of(SYNTHETIC))
 909                                         .packages(Set.of(pn, mn))
 910                                         .exports(mn)
 911                                         .build();
 912                 Module m = Modules.defineModule(ld, descriptor, null);
 913                 Modules.addReads(m, Proxy.class.getModule());
 914                 Modules.addExports(m, mn);
 915                 // java.base to create proxy instance and access its Lookup instance
 916                 Modules.addOpens(m, pn, Proxy.class.getModule());
 917                 Modules.addOpens(m, mn, Proxy.class.getModule());
 918                 return m;
 919             });
 920         }
 921     }
 922 
 923     /**
 924      * Returns a proxy instance for the specified interfaces
 925      * that dispatches method invocations to the specified invocation
 926      * handler.
 927      * <p>
 928      * <a id="restrictions">{@code IllegalArgumentException} will be thrown
 929      * if any of the following restrictions is violated:</a>
 930      * <ul>
 931      * <li>All of {@code Class} objects in the given {@code interfaces} array
 932      * must represent {@linkplain Class#isHidden() non-hidden} and
 933      * {@linkplain Class#isSealed() non-sealed} interfaces,
 934      * not classes or primitive types.
 935      *
 936      * <li>No two elements in the {@code interfaces} array may
 937      * refer to identical {@code Class} objects.
 938      *
 939      * <li>All of the interface types must be visible by name through the
 940      * specified class loader. In other words, for class loader
 941      * {@code cl} and every interface {@code i}, the following
 942      * expression must be true:<p>
 943      * {@code Class.forName(i.getName(), false, cl) == i}
 944      *
 945      * <li>All of the types referenced by all
 946      * public method signatures of the specified interfaces
 947      * and those inherited by their superinterfaces
 948      * must be visible by name through the specified class loader.
 949      *
 950      * <li>All non-public interfaces must be in the same package
 951      * and module, defined by the specified class loader and
 952      * the module of the non-public interfaces can access all of
 953      * the interface types; otherwise, it would not be possible for
 954      * the proxy class to implement all of the interfaces,
 955      * regardless of what package it is defined in.
 956      *
 957      * <li>For any set of member methods of the specified interfaces
 958      * that have the same signature:
 959      * <ul>
 960      * <li>If the return type of any of the methods is a primitive
 961      * type or void, then all of the methods must have that same
 962      * return type.
 963      * <li>Otherwise, one of the methods must have a return type that
 964      * is assignable to all of the return types of the rest of the
 965      * methods.
 966      * </ul>
 967      *
 968      * <li>The resulting proxy class must not exceed any limits imposed
 969      * on classes by the virtual machine.  For example, the VM may limit
 970      * the number of interfaces that a class may implement to 65535; in
 971      * that case, the size of the {@code interfaces} array must not
 972      * exceed 65535.
 973      * </ul>
 974      *
 975      * <p>Note that the order of the specified proxy interfaces is
 976      * significant: two requests for a proxy class with the same combination
 977      * of interfaces but in a different order will result in two distinct
 978      * proxy classes.
 979      *
 980      * @param   loader the class loader to define the proxy class
 981      * @param   interfaces the list of interfaces for the proxy class
 982      *          to implement
 983      * @param   h the invocation handler to dispatch method invocations to
 984      * @return  a proxy instance with the specified invocation handler of a
 985      *          proxy class that is defined by the specified class loader
 986      *          and that implements the specified interfaces
 987      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
 988      *          restrictions</a> on the parameters are violated
 989      * @throws  SecurityException if a security manager, <em>s</em>, is present
 990      *          and any of the following conditions is met:
 991      *          <ul>
 992      *          <li> the given {@code loader} is {@code null} and
 993      *               the caller's class loader is not {@code null} and the
 994      *               invocation of {@link SecurityManager#checkPermission
 995      *               s.checkPermission} with
 996      *               {@code RuntimePermission("getClassLoader")} permission
 997      *               denies access;</li>
 998      *          <li> for each proxy interface, {@code intf},
 999      *               the caller's class loader is not the same as or an
1000      *               ancestor of the class loader for {@code intf} and
1001      *               invocation of {@link SecurityManager#checkPackageAccess
1002      *               s.checkPackageAccess()} denies access to {@code intf};</li>
1003      *          <li> any of the given proxy interfaces is non-public and the
1004      *               caller class is not in the same {@linkplain Package runtime package}
1005      *               as the non-public interface and the invocation of
1006      *               {@link SecurityManager#checkPermission s.checkPermission} with
1007      *               {@code ReflectPermission("newProxyInPackage.{package name}")}
1008      *               permission denies access.</li>
1009      *          </ul>
1010      * @throws  NullPointerException if the {@code interfaces} array
1011      *          argument or any of its elements are {@code null}, or
1012      *          if the invocation handler, {@code h}, is
1013      *          {@code null}
1014      *
1015      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
1016      */
1017     @CallerSensitive
1018     public static Object newProxyInstance(ClassLoader loader,
1019                                           Class<?>[] interfaces,
1020                                           InvocationHandler h) {
1021         Objects.requireNonNull(h);
1022 
1023         @SuppressWarnings("removal")
1024         final Class<?> caller = System.getSecurityManager() == null
1025                                     ? null
1026                                     : Reflection.getCallerClass();
1027 
1028         /*
1029          * Look up or generate the designated proxy class and its constructor.
1030          */
1031         Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);
1032 
1033         return newProxyInstance(caller, cons, h);
1034     }
1035 
1036     private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager
1037                                            Constructor<?> cons,
1038                                            InvocationHandler h) {
1039         /*
1040          * Invoke its constructor with the designated invocation handler.
1041          */
1042         try {
1043             if (caller != null) {
1044                 checkNewProxyPermission(caller, cons.getDeclaringClass());
1045             }
1046 
1047             return cons.newInstance(new Object[]{h});
1048         } catch (IllegalAccessException | InstantiationException e) {
1049             throw new InternalError(e.toString(), e);
1050         } catch (InvocationTargetException e) {
1051             Throwable t = e.getCause();
1052             if (t instanceof RuntimeException re) {
1053                 throw re;
1054             } else {
1055                 throw new InternalError(t.toString(), t);
1056             }
1057         }
1058     }
1059 
1060     private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
1061         @SuppressWarnings("removal")
1062         SecurityManager sm = System.getSecurityManager();
1063         if (sm != null) {
1064             if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
1065                 ClassLoader ccl = caller.getClassLoader();
1066                 ClassLoader pcl = proxyClass.getClassLoader();
1067 
1068                 // do permission check if the caller is in a different runtime package
1069                 // of the proxy class
1070                 String pkg = proxyClass.getPackageName();
1071                 String callerPkg = caller.getPackageName();
1072 
1073                 if (pcl != ccl || !pkg.equals(callerPkg)) {
1074                     sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
1075                 }
1076             }
1077         }
1078     }
1079 
1080     /**
1081      * Returns the class loader for the given module.
1082      */
1083     @SuppressWarnings("removal")
1084     private static ClassLoader getLoader(Module m) {
1085         PrivilegedAction<ClassLoader> pa = m::getClassLoader;
1086         return AccessController.doPrivileged(pa);
1087     }
1088 
1089     /**
1090      * Returns true if the given class is a proxy class.
1091      *
1092      * @implNote The reliability of this method is important for the ability
1093      * to use it to make security decisions, so its implementation should
1094      * not just test if the class in question extends {@code Proxy}.
1095      *
1096      * @param   cl the class to test
1097      * @return  {@code true} if the class is a proxy class and
1098      *          {@code false} otherwise
1099      * @throws  NullPointerException if {@code cl} is {@code null}
1100      */
1101     public static boolean isProxyClass(Class<?> cl) {
1102         return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl);
1103     }
1104 
1105     /**
1106      * Returns the invocation handler for the specified proxy instance.
1107      *
1108      * @param   proxy the proxy instance to return the invocation handler for
1109      * @return  the invocation handler for the proxy instance
1110      * @throws  IllegalArgumentException if the argument is not a
1111      *          proxy instance
1112      * @throws  SecurityException if a security manager, <em>s</em>, is present
1113      *          and the caller's class loader is not the same as or an
1114      *          ancestor of the class loader for the invocation handler
1115      *          and invocation of {@link SecurityManager#checkPackageAccess
1116      *          s.checkPackageAccess()} denies access to the invocation
1117      *          handler's class.
1118      */
1119     @SuppressWarnings("removal")
1120     @CallerSensitive
1121     public static InvocationHandler getInvocationHandler(Object proxy)
1122         throws IllegalArgumentException
1123     {
1124         /*
1125          * Verify that the object is actually a proxy instance.
1126          */
1127         if (!isProxyClass(proxy.getClass())) {
1128             throw new IllegalArgumentException("not a proxy instance");
1129         }
1130 
1131         final Proxy p = (Proxy) proxy;
1132         final InvocationHandler ih = p.h;
1133         if (System.getSecurityManager() != null) {
1134             Class<?> ihClass = ih.getClass();
1135             Class<?> caller = Reflection.getCallerClass();
1136             if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
1137                                                     ihClass.getClassLoader()))
1138             {
1139                 ReflectUtil.checkPackageAccess(ihClass);
1140             }
1141         }
1142 
1143         return ih;
1144     }
1145 
1146     private static final String PROXY_PACKAGE_PREFIX = ReflectUtil.PROXY_PACKAGE;
1147 
1148     /**
1149      * A cache of Method -> MethodHandle for default methods.
1150      */
1151     private static final ClassValue<ConcurrentHashMap<Method, MethodHandle>>
1152             DEFAULT_METHODS_MAP = new ClassValue<>() {
1153         @Override
1154         protected ConcurrentHashMap<Method, MethodHandle> computeValue(Class<?> type) {
1155             return new ConcurrentHashMap<>(4);
1156         }
1157     };
1158 
1159     private static ConcurrentHashMap<Method, MethodHandle> defaultMethodMap(Class<?> proxyClass) {
1160         assert isProxyClass(proxyClass);
1161         return DEFAULT_METHODS_MAP.get(proxyClass);
1162     }
1163 
1164     static final Object[] EMPTY_ARGS = new Object[0];
1165 
1166     static MethodHandle defaultMethodHandle(Class<? extends Proxy> proxyClass, Method method) {
1167         // lookup the cached method handle
1168         ConcurrentHashMap<Method, MethodHandle> methods = defaultMethodMap(proxyClass);
1169         MethodHandle superMH = methods.get(method);
1170         if (superMH == null) {
1171             MethodType type = methodType(method.getReturnType(), method.getParameterTypes());
1172             MethodHandles.Lookup lookup = MethodHandles.lookup();
1173             Class<?> proxyInterface = findProxyInterfaceOrElseThrow(proxyClass, method);
1174             MethodHandle dmh;
1175             try {
1176                 dmh = proxyClassLookup(lookup, proxyClass)
1177                         .findSpecial(proxyInterface, method.getName(), type, proxyClass)
1178                         .withVarargs(false);
1179             } catch (IllegalAccessException | NoSuchMethodException e) {
1180                 // should not reach here
1181                 throw new InternalError(e);
1182             }
1183             // this check can be turned into assertion as it is guaranteed to succeed by the virtue of
1184             // looking up a default (instance) method declared or inherited by proxyInterface
1185             // while proxyClass implements (is a subtype of) proxyInterface ...
1186             assert ((BooleanSupplier) () -> {
1187                 try {
1188                     // make sure that the method type matches
1189                     dmh.asType(type.insertParameterTypes(0, proxyClass));
1190                     return true;
1191                 } catch (WrongMethodTypeException e) {
1192                     return false;
1193                 }
1194             }).getAsBoolean() : "Wrong method type";
1195             // change return type to Object
1196             MethodHandle mh = dmh.asType(dmh.type().changeReturnType(Object.class));
1197             // wrap any exception thrown with InvocationTargetException
1198             mh = MethodHandles.catchException(mh, Throwable.class, InvocationException.wrapMH());
1199             // spread array of arguments among parameters (skipping 1st parameter - target)
1200             mh = mh.asSpreader(1, Object[].class, type.parameterCount());
1201             // change target type to Object
1202             mh = mh.asType(MethodType.methodType(Object.class, Object.class, Object[].class));
1203 
1204             // push MH into cache
1205             MethodHandle cached = methods.putIfAbsent(method, mh);
1206             if (cached != null) {
1207                 superMH = cached;
1208             } else {
1209                 superMH = mh;
1210             }
1211         }
1212         return superMH;
1213     }
1214 
1215     /**
1216      * Finds the first proxy interface that declares the given method
1217      * directly or indirectly.
1218      *
1219      * @throws IllegalArgumentException if not found
1220      */
1221     private static Class<?> findProxyInterfaceOrElseThrow(Class<?> proxyClass, Method method) {
1222         Class<?> declaringClass = method.getDeclaringClass();
1223         if (!declaringClass.isInterface()) {
1224             throw new IllegalArgumentException("\"" + method +
1225                     "\" is not a method declared in the proxy class");
1226         }
1227 
1228         List<Class<?>> proxyInterfaces = Arrays.asList(proxyClass.getInterfaces());
1229         // the method's declaring class is a proxy interface
1230         if (proxyInterfaces.contains(declaringClass))
1231             return declaringClass;
1232 
1233         // find the first proxy interface that inherits the default method
1234         // i.e. the declaring class of the default method is a superinterface
1235         // of the proxy interface
1236         Deque<Class<?>> deque = new ArrayDeque<>();
1237         Set<Class<?>> visited = new HashSet<>();
1238         boolean indirectMethodRef = false;
1239         for (Class<?> proxyIntf : proxyInterfaces) {
1240             assert proxyIntf != declaringClass;
1241             visited.add(proxyIntf);
1242             deque.add(proxyIntf);
1243 
1244             // for each proxy interface, traverse its subinterfaces with
1245             // breadth-first search to find a subinterface declaring the
1246             // default method
1247             Class<?> c;
1248             while ((c = deque.poll()) != null) {
1249                 if (c == declaringClass) {
1250                     try {
1251                         // check if this method is the resolved method if referenced from
1252                         // this proxy interface (i.e. this method is not implemented
1253                         // by any other superinterface)
1254                         Method m = proxyIntf.getMethod(method.getName(), method.getSharedParameterTypes());
1255                         if (m.getDeclaringClass() == declaringClass) {
1256                             return proxyIntf;
1257                         }
1258                         indirectMethodRef = true;
1259                     } catch (NoSuchMethodException e) {}
1260 
1261                     // skip traversing its superinterfaces
1262                     // another proxy interface may extend it and so
1263                     // the method's declaring class is left unvisited.
1264                     continue;
1265                 }
1266                 // visit all superinterfaces of one proxy interface to find if
1267                 // this proxy interface inherits the method directly or indirectly
1268                 visited.add(c);
1269                 for (Class<?> superIntf : c.getInterfaces()) {
1270                     if (!visited.contains(superIntf) && !deque.contains(superIntf)) {
1271                         if (superIntf == declaringClass) {
1272                             // fast-path as the matching subinterface is found
1273                             deque.addFirst(superIntf);
1274                         } else {
1275                             deque.add(superIntf);
1276                         }
1277                     }
1278                 }
1279             }
1280         }
1281 
1282         throw new IllegalArgumentException("\"" + method + (indirectMethodRef
1283                 ? "\" is overridden directly or indirectly by the proxy interfaces"
1284                 : "\" is not a method declared in the proxy class"));
1285     }
1286 
1287     /**
1288      * This method invokes the proxy's proxyClassLookup method to get a
1289      * Lookup on the proxy class.
1290      *
1291      * @return a lookup for proxy class of this proxy instance
1292      */
1293     @SuppressWarnings("removal")
1294     private static MethodHandles.Lookup proxyClassLookup(MethodHandles.Lookup caller, Class<?> proxyClass) {
1295         return AccessController.doPrivileged(new PrivilegedAction<>() {
1296             @Override
1297             public MethodHandles.Lookup run() {
1298                 try {
1299                     Method m = proxyClass.getDeclaredMethod("proxyClassLookup", MethodHandles.Lookup.class);
1300                     m.setAccessible(true);
1301                     return (MethodHandles.Lookup) m.invoke(null, caller);
1302                 } catch (ReflectiveOperationException e) {
1303                     throw new InternalError(e);
1304                 }
1305             }
1306         });
1307     }
1308 
1309     /*
1310      * Invoke the default method of the given proxy with an explicit caller class.
1311      *
1312      * @throws IllegalAccessException if the proxy interface is inaccessible to the caller
1313      *         if caller is non-null
1314      */
1315     static Object invokeDefault(Object proxy, Method method, Object[] args, Class<?> caller)
1316             throws Throwable {
1317         // verify that the object is actually a proxy instance
1318         if (!Proxy.isProxyClass(proxy.getClass())) {
1319             throw new IllegalArgumentException("'proxy' is not a proxy instance");
1320         }
1321         if (!method.isDefault()) {
1322             throw new IllegalArgumentException("\"" + method + "\" is not a default method");
1323         }
1324         @SuppressWarnings("unchecked")
1325         Class<? extends Proxy> proxyClass = (Class<? extends Proxy>)proxy.getClass();
1326 
1327         // skip access check if caller is null
1328         if (caller != null) {
1329             Class<?> intf = method.getDeclaringClass();
1330             // access check on the default method
1331             method.checkAccess(caller, intf, proxyClass, method.getModifiers());
1332         }
1333 
1334         MethodHandle mh = Proxy.defaultMethodHandle(proxyClass, method);
1335         // invoke the super method
1336         try {
1337             // the args array can be null if the number of formal parameters required by
1338             // the method is zero (consistent with Method::invoke)
1339             Object[] params = args != null ? args : Proxy.EMPTY_ARGS;
1340             return mh.invokeExact(proxy, params);
1341         } catch (ClassCastException | NullPointerException e) {
1342             throw new IllegalArgumentException(e.getMessage(), e);
1343         } catch (Proxy.InvocationException e) {
1344             // unwrap and throw the exception thrown by the default method
1345             throw e.getCause();
1346         }
1347     }
1348 
1349     /**
1350      * Internal exception type to wrap the exception thrown by the default method
1351      * so that it can distinguish CCE and NPE thrown due to the arguments
1352      * incompatible with the method signature.
1353      */
1354     static class InvocationException extends ReflectiveOperationException {
1355         @java.io.Serial
1356         private static final long serialVersionUID = 0L;
1357 
1358         InvocationException(Throwable cause) {
1359             super(cause);
1360         }
1361 
1362         /**
1363          * Wraps given cause with InvocationException and throws it.
1364          */
1365         static Object wrap(Throwable cause) throws InvocationException {
1366             throw new InvocationException(cause);
1367         }
1368 
1369         @Stable
1370         static MethodHandle wrapMethodHandle;
1371 
1372         static MethodHandle wrapMH() {
1373             MethodHandle mh = wrapMethodHandle;
1374             if (mh == null) {
1375                 try {
1376                     wrapMethodHandle = mh = MethodHandles.lookup().findStatic(
1377                             InvocationException.class,
1378                             "wrap",
1379                             MethodType.methodType(Object.class, Throwable.class)
1380                     );
1381                 } catch (NoSuchMethodException | IllegalAccessException e) {
1382                     throw new InternalError(e);
1383                 }
1384             }
1385             return mh;
1386         }
1387     }
1388 
1389 }