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