1 /*
   2  * Copyright (c) 1999, 2019, 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.module.ModuleDescriptor;
  29 import java.security.AccessController;
  30 import java.security.PrivilegedAction;
  31 import java.util.Arrays;
  32 import java.util.Collections;
  33 import java.util.HashMap;
  34 import java.util.HashSet;
  35 import java.util.IdentityHashMap;
  36 import java.util.List;
  37 import java.util.Map;
  38 import java.util.Objects;
  39 import java.util.Set;
  40 import java.util.concurrent.atomic.AtomicInteger;
  41 import java.util.concurrent.atomic.AtomicLong;
  42 
  43 import jdk.internal.access.JavaLangAccess;
  44 import jdk.internal.access.SharedSecrets;
  45 import jdk.internal.loader.BootLoader;
  46 import jdk.internal.module.Modules;
  47 import jdk.internal.misc.VM;
  48 import jdk.internal.reflect.CallerSensitive;
  49 import jdk.internal.reflect.Reflection;
  50 import jdk.internal.loader.ClassLoaderValue;
  51 import sun.reflect.misc.ReflectUtil;
  52 import sun.security.action.GetBooleanAction;
  53 import sun.security.action.GetPropertyAction;
  54 import sun.security.util.SecurityConstants;
  55 
  56 import static java.lang.module.ModuleDescriptor.Modifier.SYNTHETIC;
  57 
  58 
  59 /**
  60  *
  61  * {@code Proxy} provides static methods for creating objects that act like instances
  62  * of interfaces but allow for customized method invocation.
  63  * To create a proxy instance for some interface {@code Foo}:
  64  * <pre>{@code
  65  *     InvocationHandler handler = new MyInvocationHandler(...);
  66  *     Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
  67  *                                          new Class<?>[] { Foo.class },
  68  *                                          handler);
  69  * }</pre>
  70  *
  71  * <p>
  72  * A <em>proxy class</em> is a class created at runtime that implements a specified
  73  * list of interfaces, known as <em>proxy interfaces</em>. A <em>proxy instance</em>
  74  * is an instance of a proxy class.
  75  *
  76  * Each proxy instance has an associated <i>invocation handler</i>
  77  * object, which implements the interface {@link InvocationHandler}.
  78  * A method invocation on a proxy instance through one of its proxy
  79  * interfaces will be dispatched to the {@link InvocationHandler#invoke
  80  * invoke} method of the instance's invocation handler, passing the proxy
  81  * instance, a {@code java.lang.reflect.Method} object identifying
  82  * the method that was invoked, and an array of type {@code Object}
  83  * containing the arguments.  The invocation handler processes the
  84  * encoded method invocation as appropriate and the result that it
  85  * returns will be returned as the result of the method invocation on
  86  * the proxy instance.
  87  *
  88  * <p>A proxy class has the following properties:
  89  *
  90  * <ul>
  91  * <li>The unqualified name of a proxy class is unspecified.  The space
  92  * of class names that begin with the string {@code "$Proxy"}
  93  * should be, however, reserved for proxy classes.
  94  *
  95  * <li>The package and module in which a proxy class is defined is specified
  96  * <a href="#membership">below</a>.
  97  *
  98  * <li>A proxy class is <em>final and non-abstract</em>.
  99  *
 100  * <li>A proxy class extends {@code java.lang.reflect.Proxy}.
 101  *
 102  * <li>A proxy class implements exactly the interfaces specified at its
 103  * creation, in the same order. Invoking {@link Class#getInterfaces() getInterfaces}
 104  * on its {@code Class} object will return an array containing the same
 105  * list of interfaces (in the order specified at its creation), invoking
 106  * {@link Class#getMethods getMethods} on its {@code Class} object will return
 107  * an array of {@code Method} objects that include all of the
 108  * methods in those interfaces, and invoking {@code getMethod} will
 109  * find methods in the proxy interfaces as would be expected.
 110  *
 111  * <li>The {@link java.security.ProtectionDomain} of a proxy class
 112  * is the same as that of system classes loaded by the bootstrap class
 113  * loader, such as {@code java.lang.Object}, because the code for a
 114  * proxy class is generated by trusted system code.  This protection
 115  * domain will typically be granted {@code java.security.AllPermission}.
 116  *
 117  * <li>The {@link Proxy#isProxyClass Proxy.isProxyClass} method can be used
 118  * to determine if a given class is a proxy class.
 119  * </ul>
 120  *
 121  * <p>A proxy instance has the following properties:
 122  *
 123  * <ul>
 124  * <li>Given a proxy instance {@code proxy} and one of the
 125  * interfaces, {@code Foo}, implemented by its proxy class, the
 126  * following expression will return true:
 127  * <pre>
 128  *     {@code proxy instanceof Foo}
 129  * </pre>
 130  * and the following cast operation will succeed (rather than throwing
 131  * a {@code ClassCastException}):
 132  * <pre>
 133  *     {@code (Foo) proxy}
 134  * </pre>
 135  *
 136  * <li>Each proxy instance has an associated invocation handler, the one
 137  * that was passed to its constructor.  The static
 138  * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method
 139  * will return the invocation handler associated with the proxy instance
 140  * passed as its argument.
 141  *
 142  * <li>An interface method invocation on a proxy instance will be
 143  * encoded and dispatched to the invocation handler's {@link
 144  * InvocationHandler#invoke invoke} method as described in the
 145  * documentation for that method.
 146  *
 147  * <li>An invocation of the {@code hashCode},
 148  * {@code equals}, or {@code toString} methods declared in
 149  * {@code java.lang.Object} on a proxy instance will be encoded and
 150  * dispatched to the invocation handler's {@code invoke} method in
 151  * the same manner as interface method invocations are encoded and
 152  * dispatched, as described above.  The declaring class of the
 153  * {@code Method} object passed to {@code invoke} will be
 154  * {@code java.lang.Object}.  Other public methods of a proxy
 155  * instance inherited from {@code java.lang.Object} are not
 156  * overridden by a proxy class, so invocations of those methods behave
 157  * like they do for instances of {@code java.lang.Object}.
 158  * </ul>
 159  *
 160  * <h2><a id="membership">Package and Module Membership of Proxy Class</a></h2>
 161  *
 162  * The package and module to which a proxy class belongs are chosen such that
 163  * the accessibility of the proxy class is in line with the accessibility of
 164  * the proxy interfaces. Specifically, the package and the module membership
 165  * of a proxy class defined via the
 166  * {@link Proxy#getProxyClass(ClassLoader, Class[])} or
 167  * {@link Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)}
 168  * methods is specified as follows:
 169  *
 170  * <ol>
 171  * <li>If all the proxy interfaces are in <em>exported</em> or <em>open</em>
 172  *     packages:
 173  * <ol type="a">
 174  * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is
 175  *     <em>public</em> in a package exported by the
 176  *     {@linkplain ClassLoader#getUnnamedModule() unnamed module} of the specified
 177  *     loader. The name of the package is unspecified.</li>
 178  *
 179  * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then
 180  *     the proxy class is <em>non-public</em> in the package and module of the
 181  *     non-public interfaces. All the non-public interfaces must be in the same
 182  *     package and module; otherwise, proxying them is
 183  *     <a href="#restrictions">not possible</a>.</li>
 184  * </ol>
 185  * </li>
 186  * <li>If at least one proxy interface is in a package that is
 187  *     <em>non-exported</em> and <em>non-open</em>:
 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 a <em>non-exported</em>, <em>non-open</em> package of
 191  *     <a href="#dynamicmodule"><em>dynamic module</em>.</a>
 192  *     The names of the package and the module are unspecified.</li>
 193  *
 194  * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then
 195  *     the proxy class is <em>non-public</em> in the package and module of the
 196  *     non-public interfaces. All the non-public interfaces must be in the same
 197  *     package and module; otherwise, proxying them is
 198  *     <a href="#restrictions">not possible</a>.</li>
 199  * </ol>
 200  * </li>
 201  * </ol>
 202  *
 203  * <p>
 204  * Note that if proxy interfaces with a mix of accessibilities -- for example,
 205  * an exported public interface and a non-exported non-public interface -- are
 206  * proxied by the same instance, then the proxy class's accessibility is
 207  * governed by the least accessible proxy interface.
 208  * <p>
 209  * Note that it is possible for arbitrary code to obtain access to a proxy class
 210  * in an open package with {@link AccessibleObject#setAccessible setAccessible},
 211  * whereas a proxy class in a non-open package is never accessible to
 212  * code outside the module of the proxy class.
 213  *
 214  * <p>
 215  * Throughout this specification, a "non-exported package" refers to a package
 216  * that is not exported to all modules, and a "non-open package" refers to
 217  * a package that is not open to all modules.  Specifically, these terms refer to
 218  * a package that either is not exported/open by its containing module or is
 219  * exported/open in a qualified fashion by its containing module.
 220  *
 221  * <h3><a id="dynamicmodule">Dynamic Modules</a></h3>
 222  * <p>
 223  * A dynamic module is a named module generated at runtime. A proxy class
 224  * defined in a dynamic module is encapsulated and not accessible to any module.
 225  * Calling {@link Constructor#newInstance(Object...)} on a proxy class in
 226  * a dynamic module will throw {@code IllegalAccessException};
 227  * {@code Proxy.newProxyInstance} method should be used instead.
 228  *
 229  * <p>
 230  * A dynamic module can read the modules of all of the superinterfaces of a proxy
 231  * class and the modules of the types referenced by all public method signatures
 232  * of a proxy class.  If a superinterface or a referenced type, say {@code T},
 233  * is in a non-exported package, the {@linkplain Module module} of {@code T} is
 234  * updated to export the package of {@code T} to the dynamic module.
 235  *
 236  * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3>
 237  *
 238  * <p>When two or more proxy interfaces contain a method with
 239  * the same name and parameter signature, the order of the proxy class's
 240  * interfaces becomes significant.  When such a <i>duplicate method</i>
 241  * is invoked on a proxy instance, the {@code Method} object passed
 242  * to the invocation handler will not necessarily be the one whose
 243  * declaring class is assignable from the reference type of the interface
 244  * that the proxy's method was invoked through.  This limitation exists
 245  * because the corresponding method implementation in the generated proxy
 246  * class cannot determine which interface it was invoked through.
 247  * Therefore, when a duplicate method is invoked on a proxy instance,
 248  * the {@code Method} object for the method in the foremost interface
 249  * that contains the method (either directly or inherited through a
 250  * superinterface) in the proxy class's list of interfaces is passed to
 251  * the invocation handler's {@code invoke} method, regardless of the
 252  * reference type through which the method invocation occurred.
 253  *
 254  * <p>If a proxy interface contains a method with the same name and
 255  * parameter signature as the {@code hashCode}, {@code equals},
 256  * or {@code toString} methods of {@code java.lang.Object},
 257  * when such a method is invoked on a proxy instance, the
 258  * {@code Method} object passed to the invocation handler will have
 259  * {@code java.lang.Object} as its declaring class.  In other words,
 260  * the public, non-final methods of {@code java.lang.Object}
 261  * logically precede all of the proxy interfaces for the determination of
 262  * which {@code Method} object to pass to the invocation handler.
 263  *
 264  * <p>Note also that when a duplicate method is dispatched to an
 265  * invocation handler, the {@code invoke} method may only throw
 266  * checked exception types that are assignable to one of the exception
 267  * types in the {@code throws} clause of the method in <i>all</i> of
 268  * the proxy interfaces that it can be invoked through.  If the
 269  * {@code invoke} method throws a checked exception that is not
 270  * assignable to any of the exception types declared by the method in one
 271  * of the proxy interfaces that it can be invoked through, then an
 272  * unchecked {@code UndeclaredThrowableException} will be thrown by
 273  * the invocation on the proxy instance.  This restriction means that not
 274  * all of the exception types returned by invoking
 275  * {@code getExceptionTypes} on the {@code Method} object
 276  * passed to the {@code invoke} method can necessarily be thrown
 277  * successfully by the {@code invoke} method.
 278  *
 279  * @author      Peter Jones
 280  * @see         InvocationHandler
 281  * @since       1.3
 282  * @revised 9
 283  * @spec JPMS
 284  */
 285 public class Proxy implements java.io.Serializable {
 286     @java.io.Serial
 287     private static final long serialVersionUID = -2222568056686623797L;
 288 
 289     /** parameter types of a proxy class constructor */
 290     private static final Class<?>[] constructorParams =
 291         { InvocationHandler.class };
 292 
 293     /**
 294      * a cache of proxy constructors with
 295      * {@link Constructor#setAccessible(boolean) accessible} flag already set
 296      */
 297     private static final ClassLoaderValue<Constructor<?>> proxyCache =
 298         new ClassLoaderValue<>();
 299 
 300     /**
 301      * System property to revert to generation of proxy class files for version 1.5 (V49).
 302      * Set to "true" to generate v49 class file format.
 303      */
 304     private static final boolean PROXY_GENERATOR_V49 =
 305             GetBooleanAction.privilegedGetProperty("jdk.proxy.ProxyGenerator.v49");
 306 
 307     /**
 308      * the invocation handler for this proxy instance.
 309      * @serial
 310      */
 311     protected InvocationHandler h;
 312 
 313     /**
 314      * Prohibits instantiation.
 315      */
 316     private Proxy() {
 317     }
 318 
 319     /**
 320      * Constructs a new {@code Proxy} instance from a subclass
 321      * (typically, a dynamic proxy class) with the specified value
 322      * for its invocation handler.
 323      *
 324      * @param  h the invocation handler for this proxy instance
 325      *
 326      * @throws NullPointerException if the given invocation handler, {@code h},
 327      *         is {@code null}.
 328      */
 329     protected Proxy(InvocationHandler h) {
 330         Objects.requireNonNull(h);
 331         this.h = h;
 332     }
 333 
 334     /**
 335      * Returns the {@code java.lang.Class} object for a proxy class
 336      * given a class loader and an array of interfaces.  The proxy class
 337      * will be defined by the specified class loader and will implement
 338      * all of the supplied interfaces.  If any of the given interfaces
 339      * is non-public, the proxy class will be non-public. If a proxy class
 340      * for the same permutation of interfaces has already been defined by the
 341      * class loader, then the existing proxy class will be returned; otherwise,
 342      * a proxy class for those interfaces will be generated dynamically
 343      * and defined by the class loader.
 344      *
 345      * @param   loader the class loader to define the proxy class
 346      * @param   interfaces the list of interfaces for the proxy class
 347      *          to implement
 348      * @return  a proxy class that is defined in the specified class loader
 349      *          and that implements the specified interfaces
 350      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
 351      *          restrictions</a> on the parameters are violated
 352      * @throws  SecurityException if a security manager, <em>s</em>, is present
 353      *          and any of the following conditions is met:
 354      *          <ul>
 355      *             <li> the given {@code loader} is {@code null} and
 356      *             the caller's class loader is not {@code null} and the
 357      *             invocation of {@link SecurityManager#checkPermission
 358      *             s.checkPermission} with
 359      *             {@code RuntimePermission("getClassLoader")} permission
 360      *             denies access.</li>
 361      *             <li> for each proxy interface, {@code intf},
 362      *             the caller's class loader is not the same as or an
 363      *             ancestor of the class loader for {@code intf} and
 364      *             invocation of {@link SecurityManager#checkPackageAccess
 365      *             s.checkPackageAccess()} denies access to {@code intf}.</li>
 366      *          </ul>
 367      * @throws  NullPointerException if the {@code interfaces} array
 368      *          argument or any of its elements are {@code null}
 369      *
 370      * @deprecated Proxy classes generated in a named module are encapsulated
 371      *      and not accessible to code outside its module.
 372      *      {@link Constructor#newInstance(Object...) Constructor.newInstance}
 373      *      will throw {@code IllegalAccessException} when it is called on
 374      *      an inaccessible proxy class.
 375      *      Use {@link #newProxyInstance(ClassLoader, Class[], InvocationHandler)}
 376      *      to create a proxy instance instead.
 377      *
 378      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
 379      * @revised 9
 380      * @spec JPMS
 381      */
 382     @Deprecated
 383     @CallerSensitive
 384     public static Class<?> getProxyClass(ClassLoader loader,
 385                                          Class<?>... interfaces)
 386         throws IllegalArgumentException
 387     {
 388         Class<?> caller = System.getSecurityManager() == null
 389                               ? null
 390                               : Reflection.getCallerClass();
 391 
 392         return getProxyConstructor(caller, loader, interfaces)
 393             .getDeclaringClass();
 394     }
 395 
 396     /**
 397      * Returns the {@code Constructor} object of a proxy class that takes a
 398      * single argument of type {@link InvocationHandler}, given a class loader
 399      * and an array of interfaces. The returned constructor will have the
 400      * {@link Constructor#setAccessible(boolean) accessible} flag already set.
 401      *
 402      * @param   caller passed from a public-facing @CallerSensitive method if
 403      *                 SecurityManager is set or {@code null} if there's no
 404      *                 SecurityManager
 405      * @param   loader the class loader to define the proxy class
 406      * @param   interfaces the list of interfaces for the proxy class
 407      *          to implement
 408      * @return  a Constructor of the proxy class taking single
 409      *          {@code InvocationHandler} parameter
 410      */
 411     private static Constructor<?> getProxyConstructor(Class<?> caller,
 412                                                       ClassLoader loader,
 413                                                       Class<?>... interfaces)
 414     {
 415         // optimization for single interface
 416         if (interfaces.length == 1) {
 417             Class<?> intf = interfaces[0];
 418             if (caller != null) {
 419                 checkProxyAccess(caller, loader, intf);
 420             }
 421             return proxyCache.sub(intf).computeIfAbsent(
 422                 loader,
 423                 (ld, clv) -> new ProxyBuilder(ld, clv.key()).build()
 424             );
 425         } else {
 426             // interfaces cloned
 427             final Class<?>[] intfsArray = interfaces.clone();
 428             if (caller != null) {
 429                 checkProxyAccess(caller, loader, intfsArray);
 430             }
 431             final List<Class<?>> intfs = Arrays.asList(intfsArray);
 432             return proxyCache.sub(intfs).computeIfAbsent(
 433                 loader,
 434                 (ld, clv) -> new ProxyBuilder(ld, clv.key()).build()
 435             );
 436         }
 437     }
 438 
 439     /*
 440      * Check permissions required to create a Proxy class.
 441      *
 442      * To define a proxy class, it performs the access checks as in
 443      * Class.forName (VM will invoke ClassLoader.checkPackageAccess):
 444      * 1. "getClassLoader" permission check if loader == null
 445      * 2. checkPackageAccess on the interfaces it implements
 446      *
 447      * To get a constructor and new instance of a proxy class, it performs
 448      * the package access check on the interfaces it implements
 449      * as in Class.getConstructor.
 450      *
 451      * If an interface is non-public, the proxy class must be defined by
 452      * the defining loader of the interface.  If the caller's class loader
 453      * is not the same as the defining loader of the interface, the VM
 454      * will throw IllegalAccessError when the generated proxy class is
 455      * being defined.
 456      */
 457     private static void checkProxyAccess(Class<?> caller,
 458                                          ClassLoader loader,
 459                                          Class<?> ... interfaces)
 460     {
 461         SecurityManager sm = System.getSecurityManager();
 462         if (sm != null) {
 463             ClassLoader ccl = caller.getClassLoader();
 464             if (loader == null && ccl != null) {
 465                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 466             }
 467             ReflectUtil.checkProxyPackageAccess(ccl, interfaces);
 468         }
 469     }
 470 
 471     /**
 472      * Builder for a proxy class.
 473      *
 474      * If the module is not specified in this ProxyBuilder constructor,
 475      * it will map from the given loader and interfaces to the module
 476      * in which the proxy class will be defined.
 477      */
 478     private static final class ProxyBuilder {
 479         private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
 480 
 481         // prefix for all proxy class names
 482         private static final String proxyClassNamePrefix = "$Proxy";
 483 
 484         // next number to use for generation of unique proxy class names
 485         private static final AtomicLong nextUniqueNumber = new AtomicLong();
 486 
 487         // a reverse cache of defined proxy classes
 488         private static final ClassLoaderValue<Boolean> reverseProxyCache =
 489             new ClassLoaderValue<>();
 490 
 491         private static Class<?> defineProxyClass(Module m, List<Class<?>> interfaces) {
 492             String proxyPkg = null;     // package to define proxy class in
 493             int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
 494 
 495             /*
 496              * Record the package of a non-public proxy interface so that the
 497              * proxy class will be defined in the same package.  Verify that
 498              * all non-public proxy interfaces are in the same package.
 499              */
 500             for (Class<?> intf : interfaces) {
 501                 int flags = intf.getModifiers();
 502                 if (!Modifier.isPublic(flags)) {
 503                     accessFlags = Modifier.FINAL;  // non-public, final
 504                     String pkg = intf.getPackageName();
 505                     if (proxyPkg == null) {
 506                         proxyPkg = pkg;
 507                     } else if (!pkg.equals(proxyPkg)) {
 508                         throw new IllegalArgumentException(
 509                                 "non-public interfaces from different packages");
 510                     }
 511                 }
 512             }
 513 
 514             if (proxyPkg == null) {
 515                 // all proxy interfaces are public
 516                 proxyPkg = m.isNamed() ? PROXY_PACKAGE_PREFIX + "." + m.getName()
 517                                        : PROXY_PACKAGE_PREFIX;
 518             } else if (proxyPkg.isEmpty() && m.isNamed()) {
 519                 throw new IllegalArgumentException(
 520                         "Unnamed package cannot be added to " + m);
 521             }
 522 
 523             if (m.isNamed()) {
 524                 if (!m.getDescriptor().packages().contains(proxyPkg)) {
 525                     throw new InternalError(proxyPkg + " not exist in " + m.getName());
 526                 }
 527             }
 528 
 529             /*
 530              * Choose a name for the proxy class to generate.
 531              */
 532             long num = nextUniqueNumber.getAndIncrement();
 533             String proxyName = proxyPkg.isEmpty()
 534                                     ? proxyClassNamePrefix + num
 535                                     : proxyPkg + "." + proxyClassNamePrefix + num;
 536 
 537             ClassLoader loader = getLoader(m);
 538             trace(proxyName, m, loader, interfaces);
 539 
 540             /*
 541              * Generate the specified proxy class.
 542              */
 543             byte[] proxyClassFile = PROXY_GENERATOR_V49
 544                     ? ProxyGenerator_v49.generateProxyClass(proxyName, interfaces, accessFlags)
 545                     : ProxyGenerator.generateProxyClass(loader, proxyName, interfaces, accessFlags);
 546             try {
 547                 Class<?> pc = JLA.defineClass(loader, proxyName, proxyClassFile,
 548                                               null, "__dynamic_proxy__");
 549                 reverseProxyCache.sub(pc).putIfAbsent(loader, Boolean.TRUE);
 550                 return pc;
 551             } catch (ClassFormatError e) {
 552                 /*
 553                  * A ClassFormatError here means that (barring bugs in the
 554                  * proxy class generation code) there was some other
 555                  * invalid aspect of the arguments supplied to the proxy
 556                  * class creation (such as virtual machine limitations
 557                  * exceeded).
 558                  */
 559                 throw new IllegalArgumentException(e.toString());
 560             }
 561         }
 562 
 563         /**
 564          * Test if given class is a class defined by
 565          * {@link #defineProxyClass(Module, List)}
 566          */
 567         static boolean isProxyClass(Class<?> c) {
 568             return Objects.equals(reverseProxyCache.sub(c).get(c.getClassLoader()),
 569                                   Boolean.TRUE);
 570         }
 571 
 572         private static boolean isExportedType(Class<?> c) {
 573             String pn = c.getPackageName();
 574             return Modifier.isPublic(c.getModifiers()) && c.getModule().isExported(pn);
 575         }
 576 
 577         private static boolean isPackagePrivateType(Class<?> c) {
 578             return !Modifier.isPublic(c.getModifiers());
 579         }
 580 
 581         private static String toDetails(Class<?> c) {
 582             String access = "unknown";
 583             if (isExportedType(c)) {
 584                 access = "exported";
 585             } else if (isPackagePrivateType(c)) {
 586                 access = "package-private";
 587             } else {
 588                 access = "module-private";
 589             }
 590             ClassLoader ld = c.getClassLoader();
 591             return String.format("   %s/%s %s loader %s",
 592                     c.getModule().getName(), c.getName(), access, ld);
 593         }
 594 
 595         static void trace(String cn,
 596                           Module module,
 597                           ClassLoader loader,
 598                           List<Class<?>> interfaces) {
 599             if (isDebug()) {
 600                 System.err.format("PROXY: %s/%s defined by %s%n",
 601                                   module.getName(), cn, loader);
 602             }
 603             if (isDebug("debug")) {
 604                 interfaces.forEach(c -> System.out.println(toDetails(c)));
 605             }
 606         }
 607 
 608         private static final String DEBUG =
 609             GetPropertyAction.privilegedGetProperty("jdk.proxy.debug", "");
 610 
 611         private static boolean isDebug() {
 612             return !DEBUG.isEmpty();
 613         }
 614         private static boolean isDebug(String flag) {
 615             return DEBUG.equals(flag);
 616         }
 617 
 618         // ProxyBuilder instance members start here....
 619 
 620         private final List<Class<?>> interfaces;
 621         private final Module module;
 622         ProxyBuilder(ClassLoader loader, List<Class<?>> interfaces) {
 623             if (!VM.isModuleSystemInited()) {
 624                 throw new InternalError("Proxy is not supported until "
 625                         + "module system is fully initialized");
 626             }
 627             if (interfaces.size() > 65535) {
 628                 throw new IllegalArgumentException("interface limit exceeded: "
 629                         + interfaces.size());
 630             }
 631 
 632             Set<Class<?>> refTypes = referencedTypes(loader, interfaces);
 633 
 634             // IAE if violates any restrictions specified in newProxyInstance
 635             validateProxyInterfaces(loader, interfaces, refTypes);
 636 
 637             this.interfaces = interfaces;
 638             this.module = mapToModule(loader, interfaces, refTypes);
 639             assert getLoader(module) == loader;
 640         }
 641 
 642         ProxyBuilder(ClassLoader loader, Class<?> intf) {
 643             this(loader, Collections.singletonList(intf));
 644         }
 645 
 646         /**
 647          * Generate a proxy class and return its proxy Constructor with
 648          * accessible flag already set. If the target module does not have access
 649          * to any interface types, IllegalAccessError will be thrown by the VM
 650          * at defineClass time.
 651          *
 652          * Must call the checkProxyAccess method to perform permission checks
 653          * before calling this.
 654          */
 655         Constructor<?> build() {
 656             Class<?> proxyClass = defineProxyClass(module, interfaces);
 657             final Constructor<?> cons;
 658             try {
 659                 cons = proxyClass.getConstructor(constructorParams);
 660             } catch (NoSuchMethodException e) {
 661                 throw new InternalError(e.toString(), e);
 662             }
 663             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 664                 public Void run() {
 665                     cons.setAccessible(true);
 666                     return null;
 667                 }
 668             });
 669             return cons;
 670         }
 671 
 672         /**
 673          * Validate the given proxy interfaces and the given referenced types
 674          * are visible to the defining loader.
 675          *
 676          * @throws IllegalArgumentException if it violates the restrictions
 677          *         specified in {@link Proxy#newProxyInstance}
 678          */
 679         private static void validateProxyInterfaces(ClassLoader loader,
 680                                                     List<Class<?>> interfaces,
 681                                                     Set<Class<?>> refTypes)
 682         {
 683             Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.size());
 684             for (Class<?> intf : interfaces) {
 685                 /*
 686                  * Verify that the class loader resolves the name of this
 687                  * interface to the same Class object.
 688                  */
 689                 ensureVisible(loader, intf);
 690 
 691                 /*
 692                  * Verify that the Class object actually represents an
 693                  * interface.
 694                  */
 695                 if (!intf.isInterface()) {
 696                     throw new IllegalArgumentException(intf.getName() + " is not an interface");
 697                 }
 698 
 699                 /*
 700                  * Verify that this interface is not a duplicate.
 701                  */
 702                 if (interfaceSet.put(intf, Boolean.TRUE) != null) {
 703                     throw new IllegalArgumentException("repeated interface: " + intf.getName());
 704                 }
 705             }
 706 
 707             for (Class<?> type : refTypes) {
 708                 ensureVisible(loader, type);
 709             }
 710         }
 711 
 712         /*
 713          * Returns all types referenced by all public non-static method signatures of
 714          * the proxy interfaces
 715          */
 716         private static Set<Class<?>> referencedTypes(ClassLoader loader,
 717                                                      List<Class<?>> interfaces) {
 718             var types = new HashSet<Class<?>>();
 719             for (var intf : interfaces) {
 720                 for (Method m : intf.getMethods()) {
 721                     if (!Modifier.isStatic(m.getModifiers())) {
 722                         addElementType(types, m.getReturnType());
 723                         addElementTypes(types, m.getSharedParameterTypes());
 724                         addElementTypes(types, m.getSharedExceptionTypes());
 725                     }
 726                 }
 727             }
 728             return types;
 729         }
 730 
 731         private static void addElementTypes(HashSet<Class<?>> types,
 732                                             Class<?> ... classes) {
 733             for (var cls : classes) {
 734                 addElementType(types, cls);
 735             }
 736         }
 737 
 738         private static void addElementType(HashSet<Class<?>> types,
 739                                            Class<?> cls) {
 740             var type = getElementType(cls);
 741             if (!type.isPrimitive()) {
 742                 types.add(type);
 743             }
 744         }
 745 
 746         /**
 747          * Returns the module that the generated proxy class belongs to.
 748          *
 749          * If all proxy interfaces are public and in exported packages,
 750          * then the proxy class is in unnamed module.
 751          *
 752          * If any of proxy interface is package-private, then the proxy class
 753          * is in the same module of the package-private interface.
 754          *
 755          * If all proxy interfaces are public and at least one in a non-exported
 756          * package, then the proxy class is in a dynamic module in a
 757          * non-exported package.  Reads edge and qualified exports are added
 758          * for dynamic module to access.
 759          */
 760         private static Module mapToModule(ClassLoader loader,
 761                                           List<Class<?>> interfaces,
 762                                           Set<Class<?>> refTypes) {
 763             Map<Class<?>, Module> modulePrivateTypes = new HashMap<>();
 764             Map<Class<?>, Module> packagePrivateTypes = new HashMap<>();
 765             for (Class<?> intf : interfaces) {
 766                 Module m = intf.getModule();
 767                 if (Modifier.isPublic(intf.getModifiers())) {
 768                     // module-private types
 769                     if (!m.isExported(intf.getPackageName())) {
 770                         modulePrivateTypes.put(intf, m);
 771                     }
 772                 } else {
 773                     packagePrivateTypes.put(intf, m);
 774                 }
 775             }
 776 
 777             // all proxy interfaces are public and exported, the proxy class
 778             // is in unnamed module.  Such proxy class is accessible to
 779             // any unnamed module and named module that can read unnamed module
 780             if (packagePrivateTypes.isEmpty() && modulePrivateTypes.isEmpty()) {
 781                 return loader != null ? loader.getUnnamedModule()
 782                                       : BootLoader.getUnnamedModule();
 783             }
 784 
 785             if (packagePrivateTypes.size() > 0) {
 786                 // all package-private types must be in the same runtime package
 787                 // i.e. same package name and same module (named or unnamed)
 788                 //
 789                 // Configuration will fail if M1 and in M2 defined by the same loader
 790                 // and both have the same package p (so no need to check class loader)
 791                 if (packagePrivateTypes.size() > 1 &&
 792                         (packagePrivateTypes.keySet().stream()  // more than one package
 793                                  .map(Class::getPackageName).distinct().count() > 1 ||
 794                          packagePrivateTypes.values().stream()  // or more than one module
 795                                  .distinct().count() > 1)) {
 796                     throw new IllegalArgumentException(
 797                             "non-public interfaces from different packages");
 798                 }
 799 
 800                 // all package-private types are in the same module (named or unnamed)
 801                 Module target = null;
 802                 for (Module m : packagePrivateTypes.values()) {
 803                     if (getLoader(m) != loader) {
 804                         // the specified loader is not the same class loader
 805                         // of the non-public interface
 806                         throw new IllegalArgumentException(
 807                                 "non-public interface is not defined by the given loader");
 808                     }
 809                     target = m;
 810                 }
 811 
 812                 // validate if the target module can access all other interfaces
 813                 for (Class<?> intf : interfaces) {
 814                     Module m = intf.getModule();
 815                     if (m == target) continue;
 816 
 817                     if (!target.canRead(m) || !m.isExported(intf.getPackageName(), target)) {
 818                         throw new IllegalArgumentException(target + " can't access " + intf.getName());
 819                     }
 820                 }
 821 
 822                 // return the module of the package-private interface
 823                 return target;
 824             }
 825 
 826             // All proxy interfaces are public and at least one in a non-exported
 827             // package.  So maps to a dynamic proxy module and add reads edge
 828             // and qualified exports, if necessary
 829             Module target = getDynamicModule(loader);
 830 
 831             // set up proxy class access to proxy interfaces and types
 832             // referenced in the method signature
 833             Set<Class<?>> types = new HashSet<>(interfaces);
 834             types.addAll(refTypes);
 835             for (Class<?> c : types) {
 836                 ensureAccess(target, c);
 837             }
 838             return target;
 839         }
 840 
 841         /*
 842          * Ensure the given module can access the given class.
 843          */
 844         private static void ensureAccess(Module target, Class<?> c) {
 845             Module m = c.getModule();
 846             // add read edge and qualified export for the target module to access
 847             if (!target.canRead(m)) {
 848                 Modules.addReads(target, m);
 849             }
 850             String pn = c.getPackageName();
 851             if (!m.isExported(pn, target)) {
 852                 Modules.addExports(m, pn, target);
 853             }
 854         }
 855 
 856         /*
 857          * Ensure the given class is visible to the class loader.
 858          */
 859         private static void ensureVisible(ClassLoader ld, Class<?> c) {
 860             Class<?> type = null;
 861             try {
 862                 type = Class.forName(c.getName(), false, ld);
 863             } catch (ClassNotFoundException e) {
 864             }
 865             if (type != c) {
 866                 throw new IllegalArgumentException(c.getName() +
 867                         " referenced from a method is not visible from class loader");
 868             }
 869         }
 870 
 871         private static Class<?> getElementType(Class<?> type) {
 872             Class<?> e = type;
 873             while (e.isArray()) {
 874                 e = e.getComponentType();
 875             }
 876             return e;
 877         }
 878 
 879         private static final ClassLoaderValue<Module> dynProxyModules =
 880             new ClassLoaderValue<>();
 881         private static final AtomicInteger counter = new AtomicInteger();
 882 
 883         /*
 884          * Define a dynamic module for the generated proxy classes in
 885          * a non-exported package named com.sun.proxy.$MODULE.
 886          *
 887          * Each class loader will have one dynamic module.
 888          */
 889         private static Module getDynamicModule(ClassLoader loader) {
 890             return dynProxyModules.computeIfAbsent(loader, (ld, clv) -> {
 891                 // create a dynamic module and setup module access
 892                 String mn = "jdk.proxy" + counter.incrementAndGet();
 893                 String pn = PROXY_PACKAGE_PREFIX + "." + mn;
 894                 ModuleDescriptor descriptor =
 895                     ModuleDescriptor.newModule(mn, Set.of(SYNTHETIC))
 896                                     .packages(Set.of(pn))
 897                                     .build();
 898                 Module m = Modules.defineModule(ld, descriptor, null);
 899                 Modules.addReads(m, Proxy.class.getModule());
 900                 // java.base to create proxy instance
 901                 Modules.addExports(m, pn, Object.class.getModule());
 902                 return m;
 903             });
 904         }
 905     }
 906 
 907     /**
 908      * Returns a proxy instance for the specified interfaces
 909      * that dispatches method invocations to the specified invocation
 910      * handler.
 911      * <p>
 912      * <a id="restrictions">{@code IllegalArgumentException} will be thrown
 913      * if any of the following restrictions is violated:</a>
 914      * <ul>
 915      * <li>All of {@code Class} objects in the given {@code interfaces} array
 916      * must represent interfaces, not classes or primitive types.
 917      *
 918      * <li>No two elements in the {@code interfaces} array may
 919      * refer to identical {@code Class} objects.
 920      *
 921      * <li>All of the interface types must be visible by name through the
 922      * specified class loader. In other words, for class loader
 923      * {@code cl} and every interface {@code i}, the following
 924      * expression must be true:<p>
 925      * {@code Class.forName(i.getName(), false, cl) == i}
 926      *
 927      * <li>All of the types referenced by all
 928      * public method signatures of the specified interfaces
 929      * and those inherited by their superinterfaces
 930      * must be visible by name through the specified class loader.
 931      *
 932      * <li>All non-public interfaces must be in the same package
 933      * and module, defined by the specified class loader and
 934      * the module of the non-public interfaces can access all of
 935      * the interface types; otherwise, it would not be possible for
 936      * the proxy class to implement all of the interfaces,
 937      * regardless of what package it is defined in.
 938      *
 939      * <li>For any set of member methods of the specified interfaces
 940      * that have the same signature:
 941      * <ul>
 942      * <li>If the return type of any of the methods is a primitive
 943      * type or void, then all of the methods must have that same
 944      * return type.
 945      * <li>Otherwise, one of the methods must have a return type that
 946      * is assignable to all of the return types of the rest of the
 947      * methods.
 948      * </ul>
 949      *
 950      * <li>The resulting proxy class must not exceed any limits imposed
 951      * on classes by the virtual machine.  For example, the VM may limit
 952      * the number of interfaces that a class may implement to 65535; in
 953      * that case, the size of the {@code interfaces} array must not
 954      * exceed 65535.
 955      * </ul>
 956      *
 957      * <p>Note that the order of the specified proxy interfaces is
 958      * significant: two requests for a proxy class with the same combination
 959      * of interfaces but in a different order will result in two distinct
 960      * proxy classes.
 961      *
 962      * @param   loader the class loader to define the proxy class
 963      * @param   interfaces the list of interfaces for the proxy class
 964      *          to implement
 965      * @param   h the invocation handler to dispatch method invocations to
 966      * @return  a proxy instance with the specified invocation handler of a
 967      *          proxy class that is defined by the specified class loader
 968      *          and that implements the specified interfaces
 969      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
 970      *          restrictions</a> on the parameters are violated
 971      * @throws  SecurityException if a security manager, <em>s</em>, is present
 972      *          and any of the following conditions is met:
 973      *          <ul>
 974      *          <li> the given {@code loader} is {@code null} and
 975      *               the caller's class loader is not {@code null} and the
 976      *               invocation of {@link SecurityManager#checkPermission
 977      *               s.checkPermission} with
 978      *               {@code RuntimePermission("getClassLoader")} permission
 979      *               denies access;</li>
 980      *          <li> for each proxy interface, {@code intf},
 981      *               the caller's class loader is not the same as or an
 982      *               ancestor of the class loader for {@code intf} and
 983      *               invocation of {@link SecurityManager#checkPackageAccess
 984      *               s.checkPackageAccess()} denies access to {@code intf};</li>
 985      *          <li> any of the given proxy interfaces is non-public and the
 986      *               caller class is not in the same {@linkplain Package runtime package}
 987      *               as the non-public interface and the invocation of
 988      *               {@link SecurityManager#checkPermission s.checkPermission} with
 989      *               {@code ReflectPermission("newProxyInPackage.{package name}")}
 990      *               permission denies access.</li>
 991      *          </ul>
 992      * @throws  NullPointerException if the {@code interfaces} array
 993      *          argument or any of its elements are {@code null}, or
 994      *          if the invocation handler, {@code h}, is
 995      *          {@code null}
 996      *
 997      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
 998      * @revised 9
 999      * @spec JPMS
1000      */
1001     @CallerSensitive
1002     public static Object newProxyInstance(ClassLoader loader,
1003                                           Class<?>[] interfaces,
1004                                           InvocationHandler h) {
1005         Objects.requireNonNull(h);
1006 
1007         final Class<?> caller = System.getSecurityManager() == null
1008                                     ? null
1009                                     : Reflection.getCallerClass();
1010 
1011         /*
1012          * Look up or generate the designated proxy class and its constructor.
1013          */
1014         Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);
1015 
1016         return newProxyInstance(caller, cons, h);
1017     }
1018 
1019     private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager
1020                                            Constructor<?> cons,
1021                                            InvocationHandler h) {
1022         /*
1023          * Invoke its constructor with the designated invocation handler.
1024          */
1025         try {
1026             if (caller != null) {
1027                 checkNewProxyPermission(caller, cons.getDeclaringClass());
1028             }
1029 
1030             return cons.newInstance(new Object[]{h});
1031         } catch (IllegalAccessException | InstantiationException e) {
1032             throw new InternalError(e.toString(), e);
1033         } catch (InvocationTargetException e) {
1034             Throwable t = e.getCause();
1035             if (t instanceof RuntimeException) {
1036                 throw (RuntimeException) t;
1037             } else {
1038                 throw new InternalError(t.toString(), t);
1039             }
1040         }
1041     }
1042 
1043     private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
1044         SecurityManager sm = System.getSecurityManager();
1045         if (sm != null) {
1046             if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
1047                 ClassLoader ccl = caller.getClassLoader();
1048                 ClassLoader pcl = proxyClass.getClassLoader();
1049 
1050                 // do permission check if the caller is in a different runtime package
1051                 // of the proxy class
1052                 String pkg = proxyClass.getPackageName();
1053                 String callerPkg = caller.getPackageName();
1054 
1055                 if (pcl != ccl || !pkg.equals(callerPkg)) {
1056                     sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
1057                 }
1058             }
1059         }
1060     }
1061 
1062     /**
1063      * Returns the class loader for the given module.
1064      */
1065     private static ClassLoader getLoader(Module m) {
1066         PrivilegedAction<ClassLoader> pa = m::getClassLoader;
1067         return AccessController.doPrivileged(pa);
1068     }
1069 
1070     /**
1071      * Returns true if the given class is a proxy class.
1072      *
1073      * @implNote The reliability of this method is important for the ability
1074      * to use it to make security decisions, so its implementation should
1075      * not just test if the class in question extends {@code Proxy}.
1076      *
1077      * @param   cl the class to test
1078      * @return  {@code true} if the class is a proxy class and
1079      *          {@code false} otherwise
1080      * @throws  NullPointerException if {@code cl} is {@code null}
1081      *
1082      * @revised 9
1083      * @spec JPMS
1084      */
1085     public static boolean isProxyClass(Class<?> cl) {
1086         return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl);
1087     }
1088 
1089     /**
1090      * Returns the invocation handler for the specified proxy instance.
1091      *
1092      * @param   proxy the proxy instance to return the invocation handler for
1093      * @return  the invocation handler for the proxy instance
1094      * @throws  IllegalArgumentException if the argument is not a
1095      *          proxy instance
1096      * @throws  SecurityException if a security manager, <em>s</em>, is present
1097      *          and the caller's class loader is not the same as or an
1098      *          ancestor of the class loader for the invocation handler
1099      *          and invocation of {@link SecurityManager#checkPackageAccess
1100      *          s.checkPackageAccess()} denies access to the invocation
1101      *          handler's class.
1102      */
1103     @CallerSensitive
1104     public static InvocationHandler getInvocationHandler(Object proxy)
1105         throws IllegalArgumentException
1106     {
1107         /*
1108          * Verify that the object is actually a proxy instance.
1109          */
1110         if (!isProxyClass(proxy.getClass())) {
1111             throw new IllegalArgumentException("not a proxy instance");
1112         }
1113 
1114         final Proxy p = (Proxy) proxy;
1115         final InvocationHandler ih = p.h;
1116         if (System.getSecurityManager() != null) {
1117             Class<?> ihClass = ih.getClass();
1118             Class<?> caller = Reflection.getCallerClass();
1119             if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
1120                                                     ihClass.getClassLoader()))
1121             {
1122                 ReflectUtil.checkPackageAccess(ihClass);
1123             }
1124         }
1125 
1126         return ih;
1127     }
1128 
1129     private static final String PROXY_PACKAGE_PREFIX = ReflectUtil.PROXY_PACKAGE;
1130 }