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