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             if (target == m) return;
 913 
 914             // add read edge and qualified export for the target module to access
 915             if (!target.canRead(m)) {
 916                 Modules.addReads(target, m);
 917             }
 918             String pn = c.getPackageName();
 919             if (!m.isExported(pn, target)) {
 920                 Modules.addExports(m, pn, target);
 921             }
 922         }
 923 
 924         /*
 925          * Ensure the given class is visible to the class loader.
 926          */
 927         private static void ensureVisible(ClassLoader ld, Class<?> c) {
 928             Class<?> type = null;
 929             try {
 930                 type = Class.forName(c.getName(), false, ld);
 931             } catch (ClassNotFoundException e) {
 932             }
 933             if (type != c) {
 934                 throw new IllegalArgumentException(c.getName() +
 935                         " referenced from a method is not visible from class loader: " + JLA.getLoaderNameID(ld));
 936             }
 937         }
 938 
 939         private static Class<?> getElementType(Class<?> type) {
 940             Class<?> e = type;
 941             while (e.isArray()) {
 942                 e = e.getComponentType();
 943             }
 944             return e;
 945         }
 946 
 947         private static final ClassLoaderValue<Module> dynProxyModules =
 948             new ClassLoaderValue<>();
 949         private static final AtomicInteger counter = new AtomicInteger();
 950 
 951         /*
 952          * Define a dynamic module with a package named $MODULE which
 953          * is unconditionally exported and another package named
 954          * com.sun.proxy.$MODULE which is encapsulated.
 955          *
 956          * Each class loader will have one dynamic module.
 957          */
 958         private static Module getDynamicModule(ClassLoader loader) {
 959             return dynProxyModules.computeIfAbsent(loader, (ld, clv) -> {
 960                 // create a dynamic module and setup module access
 961                 int num = counter.incrementAndGet();
 962                 String mn = "jdk.proxy" + num;
 963                 String pn = PROXY_PACKAGE_PREFIX + "." + mn;
 964                 ModuleDescriptor descriptor =
 965                         ModuleDescriptor.newModule(mn, Set.of(SYNTHETIC))
 966                                         .packages(Set.of(pn, mn))
 967                                         .exports(mn)
 968                                         .build();
 969                 Module m = Modules.defineModule(ld, descriptor, null);
 970                 openDynamicModule(m);
 971 
 972                 if (CDS.isDumpingHeap() && archivedData != null) {
 973                     archivedData.recordModule(loader, m, num);
 974                 }
 975                 return m;
 976             });
 977         }
 978 
 979         private static void openDynamicModule(Module m) {
 980             String mn = m.getName();
 981             String pn = PROXY_PACKAGE_PREFIX + "." + mn;
 982             Modules.addReads(m, Proxy.class.getModule());
 983             Modules.addExports(m, mn);
 984             // java.base to create proxy instance and access its Lookup instance
 985             Modules.addOpens(m, pn, Proxy.class.getModule());
 986             Modules.addOpens(m, mn, Proxy.class.getModule());
 987         }
 988 
 989         static class ArchivedData {
 990             static class InterfacesKey {
 991                 Class<?>[] intfsArray;
 992                 InterfacesKey(List<Class<?>> intfs) {
 993                     intfsArray = new Class<?>[intfs.size()];
 994                     for (int i = 0; i < intfs.size(); i++) {
 995                         intfsArray[i] = intfs.get(i);
 996                     }
 997                 }
 998                 @Override
 999                 public int hashCode() {
1000                     return Arrays.hashCode(intfsArray);
1001                 }
1002                 @Override
1003                 public boolean equals(Object other) {
1004                     if (other instanceof InterfacesKey) {
1005                         InterfacesKey o = (InterfacesKey)other;
1006                         int len = intfsArray.length;
1007                         if (len != o.intfsArray.length) {
1008                             return false;
1009                         }
1010                         Class<?>[] oa = o.intfsArray;
1011                         for (int i = 0; i < len; i++) {
1012                             if (intfsArray[i] != oa[i]) {
1013                                 return false;
1014                             }
1015                         }
1016                         return true;
1017                     } else {
1018                         return false;
1019                     }
1020                 }
1021             }
1022 
1023             ClassLoader platformLoader;
1024             ClassLoader appLoader;
1025             HashMap<InterfacesKey,Class<?>> bootCache = new HashMap<>();
1026             HashMap<InterfacesKey,Class<?>> platformCache = new HashMap<>();
1027             HashMap<InterfacesKey,Class<?>> appCache = new HashMap<>();
1028 
1029             Module bootModule;
1030             Module platformModule;
1031             Module appModule;
1032             int maxNum;
1033 
1034             ArchivedData(ClassLoader plat, ClassLoader app) {
1035                 platformLoader = plat;
1036                 appLoader = app;
1037             }
1038 
1039             HashMap<InterfacesKey,Class<?>> cacheForLoader(ClassLoader loader) {
1040                 if (loader == null) {
1041                     return bootCache;
1042                 } else if (loader == platformLoader) {
1043                     return platformCache;
1044                 } else if (loader == appLoader) {
1045                     return appCache;
1046                 } else {
1047                     return null;
1048                 }
1049             }
1050 
1051             void recordModule(ClassLoader loader, Module m, int num) {
1052                 if (loader == null) {
1053                     bootModule = m;
1054                 } else if (loader == platformLoader) {
1055                     platformModule = m;
1056                 } else if (loader == appLoader) {
1057                     appModule = m;
1058                 } else {
1059                     throw new UnsupportedOperationException("Class loader " + loader + " is not supported");
1060                 }
1061                 if (maxNum < num) {
1062                     maxNum = num;
1063                 }
1064             }
1065 
1066             void restore() {
1067                 // The info for addReads/addExports/addOpens are maintained solely inside the VM.
1068                 // CDS currently doesn't properly archive such info for the dynamically generated modules,
1069                 // so we have to recreate them at runtime.
1070                 //
1071                 // TODO --  consider improving CDS to archive the above info, so we can avoid calling openDynamicModule()
1072                 if (bootModule != null) {
1073                     Module last = dynProxyModules.putIfAbsent(null, bootModule);
1074                     assert last == null;
1075                     openDynamicModule(bootModule);
1076                 }
1077                 if (platformModule != null) {
1078                     Module last = dynProxyModules.putIfAbsent(platformLoader, platformModule);
1079                     assert last == null;
1080                     openDynamicModule(platformModule);
1081                 }
1082                 if (appModule != null) {
1083                     Module last = dynProxyModules.putIfAbsent(appLoader, appModule);
1084                     assert last == null;
1085                     openDynamicModule(appModule);
1086                 }
1087 
1088                 while (maxNum > counter.get()) {
1089                     counter.incrementAndGet();
1090                 }
1091             }
1092 
1093 
1094             Class<?> getArchivedProxyClass(ClassLoader loader, String proxyPrefix, List<Class<?>> interfaces) {
1095                 HashMap<InterfacesKey,Class<?>> cache = cacheForLoader(loader);
1096                 if (cache != null && cache.size() > 0) {
1097                     InterfacesKey key = new InterfacesKey(interfaces);
1098                     return cache.get(key);
1099                 } else {
1100                     return null;
1101                 }
1102             }
1103 
1104             void putArchivedProxyClass(ClassLoader loader, String proxyName, List<Class<?>> interfaces, Class<?> cls) {
1105                 HashMap<InterfacesKey,Class<?>> cache = cacheForLoader(loader);
1106                 if (cache != null) {
1107                     InterfacesKey key = new InterfacesKey(interfaces);
1108                     cache.put(key, cls);
1109                 }
1110             }
1111         }
1112 
1113         static ArchivedData archivedData;
1114 
1115         static {
1116             CDS.initializeFromArchive(ProxyBuilder.class);
1117             if (archivedData != null) {
1118                 archivedData.restore();
1119             }
1120         }
1121 
1122         private static void initCacheForCDS(ClassLoader platformLoader, ClassLoader appLoader) {
1123             archivedData = new ArchivedData(platformLoader, appLoader);
1124         }
1125     }
1126 
1127     /**
1128      * Returns a proxy instance for the specified interfaces
1129      * that dispatches method invocations to the specified invocation
1130      * handler.
1131      * <p>
1132      * <a id="restrictions">{@code IllegalArgumentException} will be thrown
1133      * if any of the following restrictions is violated:</a>
1134      * <ul>
1135      * <li>All of {@code Class} objects in the given {@code interfaces} array
1136      * must represent {@linkplain Class#isHidden() non-hidden} and
1137      * {@linkplain Class#isSealed() non-sealed} interfaces,
1138      * not classes or primitive types.
1139      *
1140      * <li>No two elements in the {@code interfaces} array may
1141      * refer to identical {@code Class} objects.
1142      *
1143      * <li>All of the interface types must be visible by name through the
1144      * specified class loader. In other words, for class loader
1145      * {@code cl} and every interface {@code i}, the following
1146      * expression must be true:<p>
1147      * {@code Class.forName(i.getName(), false, cl) == i}
1148      *
1149      * <li>All of the types referenced by all
1150      * public method signatures of the specified interfaces
1151      * and those inherited by their superinterfaces
1152      * must be visible by name through the specified class loader.
1153      *
1154      * <li>All non-public interfaces must be in the same package
1155      * and module, defined by the specified class loader and
1156      * the module of the non-public interfaces can access all of
1157      * the interface types; otherwise, it would not be possible for
1158      * the proxy class to implement all of the interfaces,
1159      * regardless of what package it is defined in.
1160      *
1161      * <li>For any set of member methods of the specified interfaces
1162      * that have the same signature:
1163      * <ul>
1164      * <li>If the return type of any of the methods is a primitive
1165      * type or void, then all of the methods must have that same
1166      * return type.
1167      * <li>Otherwise, one of the methods must have a return type that
1168      * is assignable to all of the return types of the rest of the
1169      * methods.
1170      * </ul>
1171      *
1172      * <li>The resulting proxy class must not exceed any limits imposed
1173      * on classes by the virtual machine.  For example, the VM may limit
1174      * the number of interfaces that a class may implement to 65535; in
1175      * that case, the size of the {@code interfaces} array must not
1176      * exceed 65535.
1177      * </ul>
1178      *
1179      * <p>Note that the order of the specified proxy interfaces is
1180      * significant: two requests for a proxy class with the same combination
1181      * of interfaces but in a different order will result in two distinct
1182      * proxy classes.
1183      *
1184      * @param   loader the class loader to define the proxy class
1185      * @param   interfaces the list of interfaces for the proxy class
1186      *          to implement
1187      * @param   h the invocation handler to dispatch method invocations to
1188      * @return  a proxy instance with the specified invocation handler of a
1189      *          proxy class that is defined by the specified class loader
1190      *          and that implements the specified interfaces
1191      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
1192      *          restrictions</a> on the parameters are violated
1193      * @throws  SecurityException if a security manager, <em>s</em>, is present
1194      *          and any of the following conditions is met:
1195      *          <ul>
1196      *          <li> the given {@code loader} is {@code null} and
1197      *               the caller's class loader is not {@code null} and the
1198      *               invocation of {@link SecurityManager#checkPermission
1199      *               s.checkPermission} with
1200      *               {@code RuntimePermission("getClassLoader")} permission
1201      *               denies access;</li>
1202      *          <li> for each proxy interface, {@code intf},
1203      *               the caller's class loader is not the same as or an
1204      *               ancestor of the class loader for {@code intf} and
1205      *               invocation of {@link SecurityManager#checkPackageAccess
1206      *               s.checkPackageAccess()} denies access to {@code intf};</li>
1207      *          <li> any of the given proxy interfaces is non-public and the
1208      *               caller class is not in the same {@linkplain Package runtime package}
1209      *               as the non-public interface and the invocation of
1210      *               {@link SecurityManager#checkPermission s.checkPermission} with
1211      *               {@code ReflectPermission("newProxyInPackage.{package name}")}
1212      *               permission denies access.</li>
1213      *          </ul>
1214      * @throws  NullPointerException if the {@code interfaces} array
1215      *          argument or any of its elements are {@code null}, or
1216      *          if the invocation handler, {@code h}, is
1217      *          {@code null}
1218      *
1219      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
1220      */
1221     @CallerSensitive
1222     public static Object newProxyInstance(ClassLoader loader,
1223                                           Class<?>[] interfaces,
1224                                           InvocationHandler h) {
1225         Objects.requireNonNull(h);
1226 
1227         @SuppressWarnings("removal")
1228         final Class<?> caller = System.getSecurityManager() == null
1229                                     ? null
1230                                     : Reflection.getCallerClass();
1231 
1232         /*
1233          * Look up or generate the designated proxy class and its constructor.
1234          */
1235         Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);
1236 
1237         return newProxyInstance(caller, cons, h);
1238     }
1239 
1240     private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager
1241                                            Constructor<?> cons,
1242                                            InvocationHandler h) {
1243         /*
1244          * Invoke its constructor with the designated invocation handler.
1245          */
1246         try {
1247             if (caller != null) {
1248                 checkNewProxyPermission(caller, cons.getDeclaringClass());
1249             }
1250 
1251             return cons.newInstance(new Object[]{h});
1252         } catch (IllegalAccessException | InstantiationException e) {
1253             throw new InternalError(e.toString(), e);
1254         } catch (InvocationTargetException e) {
1255             Throwable t = e.getCause();
1256             if (t instanceof RuntimeException re) {
1257                 throw re;
1258             } else {
1259                 throw new InternalError(t.toString(), t);
1260             }
1261         }
1262     }
1263 
1264     private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
1265         @SuppressWarnings("removal")
1266         SecurityManager sm = System.getSecurityManager();
1267         if (sm != null) {
1268             if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
1269                 ClassLoader ccl = caller.getClassLoader();
1270                 ClassLoader pcl = proxyClass.getClassLoader();
1271 
1272                 // do permission check if the caller is in a different runtime package
1273                 // of the proxy class
1274                 String pkg = proxyClass.getPackageName();
1275                 String callerPkg = caller.getPackageName();
1276 
1277                 if (pcl != ccl || !pkg.equals(callerPkg)) {
1278                     sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
1279                 }
1280             }
1281         }
1282     }
1283 
1284     /**
1285      * Returns the class loader for the given module.
1286      */
1287     @SuppressWarnings("removal")
1288     private static ClassLoader getLoader(Module m) {
1289         PrivilegedAction<ClassLoader> pa = m::getClassLoader;
1290         return AccessController.doPrivileged(pa);
1291     }
1292 
1293     /**
1294      * Returns true if the given class is a proxy class.
1295      *
1296      * @implNote The reliability of this method is important for the ability
1297      * to use it to make security decisions, so its implementation should
1298      * not just test if the class in question extends {@code Proxy}.
1299      *
1300      * @param   cl the class to test
1301      * @return  {@code true} if the class is a proxy class and
1302      *          {@code false} otherwise
1303      * @throws  NullPointerException if {@code cl} is {@code null}
1304      */
1305     public static boolean isProxyClass(Class<?> cl) {
1306         return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl);
1307     }
1308 
1309     /**
1310      * Returns the invocation handler for the specified proxy instance.
1311      *
1312      * @param   proxy the proxy instance to return the invocation handler for
1313      * @return  the invocation handler for the proxy instance
1314      * @throws  IllegalArgumentException if the argument is not a
1315      *          proxy instance
1316      * @throws  SecurityException if a security manager, <em>s</em>, is present
1317      *          and the caller's class loader is not the same as or an
1318      *          ancestor of the class loader for the invocation handler
1319      *          and invocation of {@link SecurityManager#checkPackageAccess
1320      *          s.checkPackageAccess()} denies access to the invocation
1321      *          handler's class.
1322      */
1323     @SuppressWarnings("removal")
1324     @CallerSensitive
1325     public static InvocationHandler getInvocationHandler(Object proxy)
1326         throws IllegalArgumentException
1327     {
1328         /*
1329          * Verify that the object is actually a proxy instance.
1330          */
1331         if (!isProxyClass(proxy.getClass())) {
1332             throw new IllegalArgumentException("not a proxy instance");
1333         }
1334 
1335         final Proxy p = (Proxy) proxy;
1336         final InvocationHandler ih = p.h;
1337         if (System.getSecurityManager() != null) {
1338             Class<?> ihClass = ih.getClass();
1339             Class<?> caller = Reflection.getCallerClass();
1340             if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
1341                                                     ihClass.getClassLoader()))
1342             {
1343                 ReflectUtil.checkPackageAccess(ihClass);
1344             }
1345         }
1346 
1347         return ih;
1348     }
1349 
1350     private static final String PROXY_PACKAGE_PREFIX = ReflectUtil.PROXY_PACKAGE;
1351 
1352     /**
1353      * A cache of Method -> MethodHandle for default methods.
1354      */
1355     private static final ClassValue<ConcurrentHashMap<Method, MethodHandle>>
1356             DEFAULT_METHODS_MAP = new ClassValue<>() {
1357         @Override
1358         protected ConcurrentHashMap<Method, MethodHandle> computeValue(Class<?> type) {
1359             return new ConcurrentHashMap<>(4);
1360         }
1361     };
1362 
1363     private static ConcurrentHashMap<Method, MethodHandle> defaultMethodMap(Class<?> proxyClass) {
1364         assert isProxyClass(proxyClass);
1365         return DEFAULT_METHODS_MAP.get(proxyClass);
1366     }
1367 
1368     static final Object[] EMPTY_ARGS = new Object[0];
1369 
1370     static MethodHandle defaultMethodHandle(Class<? extends Proxy> proxyClass, Method method) {
1371         // lookup the cached method handle
1372         ConcurrentHashMap<Method, MethodHandle> methods = defaultMethodMap(proxyClass);
1373         MethodHandle superMH = methods.get(method);
1374         if (superMH == null) {
1375             MethodType type = methodType(method.getReturnType(), method.getParameterTypes());
1376             MethodHandles.Lookup lookup = MethodHandles.lookup();
1377             Class<?> proxyInterface = findProxyInterfaceOrElseThrow(proxyClass, method);
1378             MethodHandle dmh;
1379             try {
1380                 dmh = proxyClassLookup(lookup, proxyClass)
1381                         .findSpecial(proxyInterface, method.getName(), type, proxyClass)
1382                         .withVarargs(false);
1383             } catch (IllegalAccessException | NoSuchMethodException e) {
1384                 // should not reach here
1385                 throw new InternalError(e);
1386             }
1387             // this check can be turned into assertion as it is guaranteed to succeed by the virtue of
1388             // looking up a default (instance) method declared or inherited by proxyInterface
1389             // while proxyClass implements (is a subtype of) proxyInterface ...
1390             assert ((BooleanSupplier) () -> {
1391                 try {
1392                     // make sure that the method type matches
1393                     dmh.asType(type.insertParameterTypes(0, proxyClass));
1394                     return true;
1395                 } catch (WrongMethodTypeException e) {
1396                     return false;
1397                 }
1398             }).getAsBoolean() : "Wrong method type";
1399             // change return type to Object
1400             MethodHandle mh = dmh.asType(dmh.type().changeReturnType(Object.class));
1401             // wrap any exception thrown with InvocationTargetException
1402             mh = MethodHandles.catchException(mh, Throwable.class, InvocationException.wrapMH());
1403             // spread array of arguments among parameters (skipping 1st parameter - target)
1404             mh = mh.asSpreader(1, Object[].class, type.parameterCount());
1405             // change target type to Object
1406             mh = mh.asType(MethodType.methodType(Object.class, Object.class, Object[].class));
1407 
1408             // push MH into cache
1409             MethodHandle cached = methods.putIfAbsent(method, mh);
1410             if (cached != null) {
1411                 superMH = cached;
1412             } else {
1413                 superMH = mh;
1414             }
1415         }
1416         return superMH;
1417     }
1418 
1419     /**
1420      * Finds the first proxy interface that declares the given method
1421      * directly or indirectly.
1422      *
1423      * @throws IllegalArgumentException if not found
1424      */
1425     private static Class<?> findProxyInterfaceOrElseThrow(Class<?> proxyClass, Method method) {
1426         Class<?> declaringClass = method.getDeclaringClass();
1427         if (!declaringClass.isInterface()) {
1428             throw new IllegalArgumentException("\"" + method +
1429                     "\" is not a method declared in the proxy class");
1430         }
1431 
1432         List<Class<?>> proxyInterfaces = Arrays.asList(proxyClass.getInterfaces());
1433         // the method's declaring class is a proxy interface
1434         if (proxyInterfaces.contains(declaringClass))
1435             return declaringClass;
1436 
1437         // find the first proxy interface that inherits the default method
1438         // i.e. the declaring class of the default method is a superinterface
1439         // of the proxy interface
1440         Deque<Class<?>> deque = new ArrayDeque<>();
1441         Set<Class<?>> visited = new HashSet<>();
1442         boolean indirectMethodRef = false;
1443         for (Class<?> proxyIntf : proxyInterfaces) {
1444             assert proxyIntf != declaringClass;
1445             visited.add(proxyIntf);
1446             deque.add(proxyIntf);
1447 
1448             // for each proxy interface, traverse its subinterfaces with
1449             // breadth-first search to find a subinterface declaring the
1450             // default method
1451             Class<?> c;
1452             while ((c = deque.poll()) != null) {
1453                 if (c == declaringClass) {
1454                     try {
1455                         // check if this method is the resolved method if referenced from
1456                         // this proxy interface (i.e. this method is not implemented
1457                         // by any other superinterface)
1458                         Method m = proxyIntf.getMethod(method.getName(), method.getSharedParameterTypes());
1459                         if (m.getDeclaringClass() == declaringClass) {
1460                             return proxyIntf;
1461                         }
1462                         indirectMethodRef = true;
1463                     } catch (NoSuchMethodException e) {}
1464 
1465                     // skip traversing its superinterfaces
1466                     // another proxy interface may extend it and so
1467                     // the method's declaring class is left unvisited.
1468                     continue;
1469                 }
1470                 // visit all superinterfaces of one proxy interface to find if
1471                 // this proxy interface inherits the method directly or indirectly
1472                 visited.add(c);
1473                 for (Class<?> superIntf : c.getInterfaces()) {
1474                     if (!visited.contains(superIntf) && !deque.contains(superIntf)) {
1475                         if (superIntf == declaringClass) {
1476                             // fast-path as the matching subinterface is found
1477                             deque.addFirst(superIntf);
1478                         } else {
1479                             deque.add(superIntf);
1480                         }
1481                     }
1482                 }
1483             }
1484         }
1485 
1486         throw new IllegalArgumentException("\"" + method + (indirectMethodRef
1487                 ? "\" is overridden directly or indirectly by the proxy interfaces"
1488                 : "\" is not a method declared in the proxy class"));
1489     }
1490 
1491     /**
1492      * This method invokes the proxy's proxyClassLookup method to get a
1493      * Lookup on the proxy class.
1494      *
1495      * @return a lookup for proxy class of this proxy instance
1496      */
1497     @SuppressWarnings("removal")
1498     private static MethodHandles.Lookup proxyClassLookup(MethodHandles.Lookup caller, Class<?> proxyClass) {
1499         return AccessController.doPrivileged(new PrivilegedAction<>() {
1500             @Override
1501             public MethodHandles.Lookup run() {
1502                 try {
1503                     Method m = proxyClass.getDeclaredMethod("proxyClassLookup", MethodHandles.Lookup.class);
1504                     m.setAccessible(true);
1505                     return (MethodHandles.Lookup) m.invoke(null, caller);
1506                 } catch (ReflectiveOperationException e) {
1507                     throw new InternalError(e);
1508                 }
1509             }
1510         });
1511     }
1512 
1513     /*
1514      * Invoke the default method of the given proxy with an explicit caller class.
1515      *
1516      * @throws IllegalAccessException if the proxy interface is inaccessible to the caller
1517      *         if caller is non-null
1518      */
1519     static Object invokeDefault(Object proxy, Method method, Object[] args, Class<?> caller)
1520             throws Throwable {
1521         // verify that the object is actually a proxy instance
1522         if (!Proxy.isProxyClass(proxy.getClass())) {
1523             throw new IllegalArgumentException("'proxy' is not a proxy instance");
1524         }
1525         if (!method.isDefault()) {
1526             throw new IllegalArgumentException("\"" + method + "\" is not a default method");
1527         }
1528         @SuppressWarnings("unchecked")
1529         Class<? extends Proxy> proxyClass = (Class<? extends Proxy>)proxy.getClass();
1530 
1531         // skip access check if caller is null
1532         if (caller != null) {
1533             Class<?> intf = method.getDeclaringClass();
1534             // access check on the default method
1535             method.checkAccess(caller, intf, proxyClass, method.getModifiers());
1536         }
1537 
1538         MethodHandle mh = Proxy.defaultMethodHandle(proxyClass, method);
1539         // invoke the super method
1540         try {
1541             // the args array can be null if the number of formal parameters required by
1542             // the method is zero (consistent with Method::invoke)
1543             Object[] params = args != null ? args : Proxy.EMPTY_ARGS;
1544             return mh.invokeExact(proxy, params);
1545         } catch (ClassCastException | NullPointerException e) {
1546             throw new IllegalArgumentException(e.getMessage(), e);
1547         } catch (Proxy.InvocationException e) {
1548             // unwrap and throw the exception thrown by the default method
1549             throw e.getCause();
1550         }
1551     }
1552 
1553     /**
1554      * Internal exception type to wrap the exception thrown by the default method
1555      * so that it can distinguish CCE and NPE thrown due to the arguments
1556      * incompatible with the method signature.
1557      */
1558     static class InvocationException extends ReflectiveOperationException {
1559         @java.io.Serial
1560         private static final long serialVersionUID = 0L;
1561 
1562         InvocationException(Throwable cause) {
1563             super(cause);
1564         }
1565 
1566         /**
1567          * Wraps given cause with InvocationException and throws it.
1568          */
1569         static Object wrap(Throwable cause) throws InvocationException {
1570             throw new InvocationException(cause);
1571         }
1572 
1573         @Stable
1574         static MethodHandle wrapMethodHandle;
1575 
1576         static MethodHandle wrapMH() {
1577             MethodHandle mh = wrapMethodHandle;
1578             if (mh == null) {
1579                 try {
1580                     wrapMethodHandle = mh = MethodHandles.lookup().findStatic(
1581                             InvocationException.class,
1582                             "wrap",
1583                             MethodType.methodType(Object.class, Throwable.class)
1584                     );
1585                 } catch (NoSuchMethodException | IllegalAccessException e) {
1586                     throw new InternalError(e);
1587                 }
1588             }
1589             return mh;
1590         }
1591     }
1592 
1593 }