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