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