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