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