1 /*
   2  * Copyright (c) 1999, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.reflect;
  27 
  28 import java.lang.invoke.MethodHandle;
  29 import java.lang.invoke.MethodHandles;
  30 import java.lang.invoke.MethodType;
  31 import java.lang.invoke.WrongMethodTypeException;
  32 import java.lang.module.ModuleDescriptor;
  33 import java.security.AccessController;
  34 import java.security.PrivilegedAction;
  35 import java.util.ArrayDeque;
  36 import java.util.Arrays;
  37 import java.util.Collections;
  38 import java.util.Deque;
  39 import java.util.HashMap;
  40 import java.util.HashSet;
  41 import java.util.IdentityHashMap;
  42 import java.util.List;
  43 import java.util.Map;
  44 import java.util.Objects;
  45 import java.util.Set;
  46 import java.util.concurrent.ConcurrentHashMap;
  47 import java.util.concurrent.atomic.AtomicInteger;
  48 import java.util.concurrent.atomic.AtomicLong;
  49 import java.util.function.BooleanSupplier;
  50 
  51 import jdk.internal.access.JavaLangAccess;
  52 import jdk.internal.access.SharedSecrets;
  53 import jdk.internal.module.Modules;
  54 import jdk.internal.misc.VM;
  55 import jdk.internal.reflect.CallerSensitive;
  56 import jdk.internal.reflect.Reflection;
  57 import jdk.internal.loader.ClassLoaderValue;
  58 import jdk.internal.vm.annotation.Stable;
  59 import sun.reflect.misc.ReflectUtil;
  60 import sun.security.action.GetPropertyAction;
  61 import sun.security.util.SecurityConstants;
  62 
  63 import static java.lang.invoke.MethodType.methodType;
  64 import static java.lang.module.ModuleDescriptor.Modifier.SYNTHETIC;
  65 
  66 /**
  67  *
  68  * {@code Proxy} provides static methods for creating objects that act like instances
  69  * of interfaces but allow for customized method invocation.
  70  * To create a proxy instance for some interface {@code Foo}:
  71  * <pre>{@code
  72  *     InvocationHandler handler = new MyInvocationHandler(...);
  73  *     Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
  74  *                                          new Class<?>[] { Foo.class },
  75  *                                          handler);
  76  * }</pre>
  77  *
  78  * <p>
  79  * A <em>proxy class</em> is a class created at runtime that implements a specified
  80  * list of interfaces, known as <em>proxy interfaces</em>. A <em>proxy instance</em>
  81  * is an instance of a proxy class.
  82  *
  83  * Each proxy instance has an associated <i>invocation handler</i>
  84  * object, which implements the interface {@link InvocationHandler}.
  85  * A method invocation on a proxy instance through one of its proxy
  86  * interfaces will be dispatched to the {@link InvocationHandler#invoke
  87  * invoke} method of the instance's invocation handler, passing the proxy
  88  * instance, a {@code java.lang.reflect.Method} object identifying
  89  * the method that was invoked, and an array of type {@code Object}
  90  * containing the arguments.  The invocation handler processes the
  91  * encoded method invocation as appropriate and the result that it
  92  * returns will be returned as the result of the method invocation on
  93  * the proxy instance.
  94  *
  95  * <p>A proxy class has the following properties:
  96  *
  97  * <ul>
  98  * <li>The unqualified name of a proxy class is unspecified.  The space
  99  * of class names that begin with the string {@code "$Proxy"}
 100  * should be, however, reserved for proxy classes.
 101  *
 102  * <li>The package and module in which a proxy class is defined is specified
 103  * <a href="#membership">below</a>.
 104  *
 105  * <li>A proxy class is <em>final and non-abstract</em>.
 106  *
 107  * <li>A proxy class extends {@code java.lang.reflect.Proxy}.
 108  *
 109  * <li>A proxy class implements exactly the interfaces specified at its
 110  * creation, in the same order. Invoking {@link Class#getInterfaces() getInterfaces}
 111  * on its {@code Class} object will return an array containing the same
 112  * list of interfaces (in the order specified at its creation), invoking
 113  * {@link Class#getMethods getMethods} on its {@code Class} object will return
 114  * an array of {@code Method} objects that include all of the
 115  * methods in those interfaces, and invoking {@code getMethod} will
 116  * find methods in the proxy interfaces as would be expected.
 117  *
 118  * <li>The {@link java.security.ProtectionDomain} of a proxy class
 119  * is the same as that of system classes loaded by the bootstrap class
 120  * loader, such as {@code java.lang.Object}, because the code for a
 121  * proxy class is generated by trusted system code.  This protection
 122  * domain will typically be granted {@code java.security.AllPermission}.
 123  *
 124  * <li>The {@link Proxy#isProxyClass Proxy.isProxyClass} method can be used
 125  * to determine if a given class is a proxy class.
 126  * </ul>
 127  *
 128  * <p>A proxy instance has the following properties:
 129  *
 130  * <ul>
 131  * <li>Given a proxy instance {@code proxy} and one of the
 132  * interfaces, {@code Foo}, implemented by its proxy class, the
 133  * following expression will return true:
 134  * <pre>
 135  *     {@code proxy instanceof Foo}
 136  * </pre>
 137  * and the following cast operation will succeed (rather than throwing
 138  * a {@code ClassCastException}):
 139  * <pre>
 140  *     {@code (Foo) proxy}
 141  * </pre>
 142  *
 143  * <li>Each proxy instance has an associated invocation handler, the one
 144  * that was passed to its constructor.  The static
 145  * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method
 146  * will return the invocation handler associated with the proxy instance
 147  * passed as its argument.
 148  *
 149  * <li>An interface method invocation on a proxy instance will be
 150  * encoded and dispatched to the invocation handler's {@link
 151  * InvocationHandler#invoke invoke} method as described in the
 152  * documentation for that method.
 153  *
 154  * <li>A proxy interface may define a default method or inherit
 155  * a default method from its superinterface directly or indirectly.
 156  * An invocation handler can invoke a default method of a proxy interface
 157  * by calling {@link InvocationHandler#invokeDefault(Object, Method, Object...)
 158  * InvocationHandler::invokeDefault}.
 159  *
 160  * <li>An invocation of the {@code hashCode},
 161  * {@code equals}, or {@code toString} methods declared in
 162  * {@code java.lang.Object} on a proxy instance will be encoded and
 163  * dispatched to the invocation handler's {@code invoke} method in
 164  * the same manner as interface method invocations are encoded and
 165  * dispatched, as described above.  The declaring class of the
 166  * {@code Method} object passed to {@code invoke} will be
 167  * {@code java.lang.Object}.  Other public methods of a proxy
 168  * instance inherited from {@code java.lang.Object} are not
 169  * overridden by a proxy class, so invocations of those methods behave
 170  * like they do for instances of {@code java.lang.Object}.
 171  * </ul>
 172  *
 173  * <h2><a id="membership">Package and Module Membership of Proxy Class</a></h2>
 174  *
 175  * The package and module to which a proxy class belongs are chosen such that
 176  * the accessibility of the proxy class is in line with the accessibility of
 177  * the proxy interfaces. Specifically, the package and the module membership
 178  * of a proxy class defined via the
 179  * {@link Proxy#getProxyClass(ClassLoader, Class[])} or
 180  * {@link Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)}
 181  * methods is specified as follows:
 182  *
 183  * <ol>
 184  * <li>If all the proxy interfaces are in <em>exported</em> or <em>open</em>
 185  *     packages:
 186  * <ol type="a">
 187  * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is
 188  *     <em>public</em> in an unconditionally exported but non-open package.
 189  *     The name of the package and the module are unspecified.</li>
 190  *
 191  * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then
 192  *     the proxy class is <em>non-public</em> in the package and module of the
 193  *     non-public interfaces. All the non-public interfaces must be in the same
 194  *     package and module; otherwise, proxying them is
 195  *     <a href="#restrictions">not possible</a>.</li>
 196  * </ol>
 197  * </li>
 198  * <li>If at least one proxy interface is in a package that is
 199  *     <em>non-exported</em> and <em>non-open</em>:
 200  * <ol type="a">
 201  * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is
 202  *     <em>public</em> in a <em>non-exported</em>, <em>non-open</em> package of
 203  *     <a href="#dynamicmodule"><em>dynamic module</em>.</a>
 204  *     The names of the package and the module are unspecified.</li>
 205  *
 206  * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then
 207  *     the proxy class is <em>non-public</em> in the package and module of the
 208  *     non-public interfaces. All the non-public interfaces must be in the same
 209  *     package and module; otherwise, proxying them is
 210  *     <a href="#restrictions">not possible</a>.</li>
 211  * </ol>
 212  * </li>
 213  * </ol>
 214  *
 215  * <p>
 216  * Note that if proxy interfaces with a mix of accessibilities -- for example,
 217  * an exported public interface and a non-exported non-public interface -- are
 218  * proxied by the same instance, then the proxy class's accessibility is
 219  * governed by the least accessible proxy interface.
 220  * <p>
 221  * Note that it is possible for arbitrary code to obtain access to a proxy class
 222  * in an open package with {@link AccessibleObject#setAccessible setAccessible},
 223  * whereas a proxy class in a non-open package is never accessible to
 224  * code outside the module of the proxy class.
 225  *
 226  * <p>
 227  * Throughout this specification, a "non-exported package" refers to a package
 228  * that is not exported to all modules, and a "non-open package" refers to
 229  * a package that is not open to all modules.  Specifically, these terms refer to
 230  * a package that either is not exported/open by its containing module or is
 231  * exported/open in a qualified fashion by its containing module.
 232  *
 233  * <h3><a id="dynamicmodule">Dynamic Modules</a></h3>
 234  * <p>
 235  * A dynamic module is a named module generated at runtime. A proxy class
 236  * defined in a dynamic module is encapsulated and not accessible to any module.
 237  * Calling {@link Constructor#newInstance(Object...)} on a proxy class in
 238  * a dynamic module will throw {@code IllegalAccessException};
 239  * {@code Proxy.newProxyInstance} method should be used instead.
 240  *
 241  * <p>
 242  * A dynamic module can read the modules of all of the superinterfaces of a proxy
 243  * class and the modules of the classes and interfaces referenced by
 244  * all public method signatures of a proxy class.  If a superinterface or
 245  * a referenced class or interface, say {@code T}, is in a non-exported package,
 246  * the {@linkplain Module module} of {@code T} is updated to export the
 247  * package of {@code T} to the dynamic module.
 248  *
 249  * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3>
 250  *
 251  * <p>When two or more proxy interfaces contain a method with
 252  * the same name and parameter signature, the order of the proxy class's
 253  * interfaces becomes significant.  When such a <i>duplicate method</i>
 254  * is invoked on a proxy instance, the {@code Method} object passed
 255  * to the invocation handler will not necessarily be the one whose
 256  * declaring class is assignable from the reference type of the interface
 257  * that the proxy's method was invoked through.  This limitation exists
 258  * because the corresponding method implementation in the generated proxy
 259  * class cannot determine which interface it was invoked through.
 260  * Therefore, when a duplicate method is invoked on a proxy instance,
 261  * the {@code Method} object for the method in the foremost interface
 262  * that contains the method (either directly or inherited through a
 263  * superinterface) in the proxy class's list of interfaces is passed to
 264  * the invocation handler's {@code invoke} method, regardless of the
 265  * reference type through which the method invocation occurred.
 266  *
 267  * <p>If a proxy interface contains a method with the same name and
 268  * parameter signature as the {@code hashCode}, {@code equals},
 269  * or {@code toString} methods of {@code java.lang.Object},
 270  * when such a method is invoked on a proxy instance, the
 271  * {@code Method} object passed to the invocation handler will have
 272  * {@code java.lang.Object} as its declaring class.  In other words,
 273  * the public, non-final methods of {@code java.lang.Object}
 274  * logically precede all of the proxy interfaces for the determination of
 275  * which {@code Method} object to pass to the invocation handler.
 276  *
 277  * <p>Note also that when a duplicate method is dispatched to an
 278  * invocation handler, the {@code invoke} method may only throw
 279  * checked exception types that are assignable to one of the exception
 280  * types in the {@code throws} clause of the method in <i>all</i> of
 281  * the proxy interfaces that it can be invoked through.  If the
 282  * {@code invoke} method throws a checked exception that is not
 283  * assignable to any of the exception types declared by the method in one
 284  * of the proxy interfaces that it can be invoked through, then an
 285  * unchecked {@code UndeclaredThrowableException} will be thrown by
 286  * the invocation on the proxy instance.  This restriction means that not
 287  * all of the exception types returned by invoking
 288  * {@code getExceptionTypes} on the {@code Method} object
 289  * passed to the {@code invoke} method can necessarily be thrown
 290  * successfully by the {@code invoke} method.
 291  *
 292  * @author      Peter Jones
 293  * @see         InvocationHandler
 294  * @since       1.3
 295  * @revised 9
 296  */
 297 public class Proxy implements java.io.Serializable {
 298     @java.io.Serial
 299     private static final long serialVersionUID = -2222568056686623797L;
 300 
 301     /** parameter types of a proxy class constructor */
 302     private static final Class<?>[] constructorParams =
 303         { InvocationHandler.class };
 304 
 305     /**
 306      * a cache of proxy constructors with
 307      * {@link Constructor#setAccessible(boolean) accessible} flag already set
 308      */
 309     private static final ClassLoaderValue<Constructor<?>> proxyCache =
 310         new ClassLoaderValue<>();
 311 
 312     /**
 313      * the invocation handler for this proxy instance.
 314      * @serial
 315      */
 316     @SuppressWarnings("serial") // Not statically typed as Serializable
 317     protected InvocationHandler h;
 318 
 319     /**
 320      * Prohibits instantiation.
 321      */
 322     private Proxy() {
 323     }
 324 
 325     /**
 326      * Constructs a new {@code Proxy} instance from a subclass
 327      * (typically, a dynamic proxy class) with the specified value
 328      * for its invocation handler.
 329      *
 330      * @param  h the invocation handler for this proxy instance
 331      *
 332      * @throws NullPointerException if the given invocation handler, {@code h},
 333      *         is {@code null}.
 334      */
 335     protected Proxy(InvocationHandler h) {
 336         Objects.requireNonNull(h);
 337         this.h = h;
 338     }
 339 
 340     /**
 341      * Returns the {@code java.lang.Class} object for a proxy class
 342      * given a class loader and an array of interfaces.  The proxy class
 343      * will be defined by the specified class loader and will implement
 344      * all of the supplied interfaces.  If any of the given interfaces
 345      * is non-public, the proxy class will be non-public. If a proxy class
 346      * for the same permutation of interfaces has already been defined by the
 347      * class loader, then the existing proxy class will be returned; otherwise,
 348      * a proxy class for those interfaces will be generated dynamically
 349      * and defined by the class loader.
 350      *
 351      * @param   loader the class loader to define the proxy class
 352      * @param   interfaces the list of interfaces for the proxy class
 353      *          to implement
 354      * @return  a proxy class that is defined in the specified class loader
 355      *          and that implements the specified interfaces
 356      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
 357      *          restrictions</a> on the parameters are violated
 358      * @throws  SecurityException if a security manager, <em>s</em>, is present
 359      *          and any of the following conditions is met:
 360      *          <ul>
 361      *             <li> the given {@code loader} is {@code null} and
 362      *             the caller's class loader is not {@code null} and the
 363      *             invocation of {@link SecurityManager#checkPermission
 364      *             s.checkPermission} with
 365      *             {@code RuntimePermission("getClassLoader")} permission
 366      *             denies access.</li>
 367      *             <li> for each proxy interface, {@code intf},
 368      *             the caller's class loader is not the same as or an
 369      *             ancestor of the class loader for {@code intf} and
 370      *             invocation of {@link SecurityManager#checkPackageAccess
 371      *             s.checkPackageAccess()} denies access to {@code intf}.</li>
 372      *          </ul>
 373      * @throws  NullPointerException if the {@code interfaces} array
 374      *          argument or any of its elements are {@code null}
 375      *
 376      * @deprecated Proxy classes generated in a named module are encapsulated
 377      *      and not accessible to code outside its module.
 378      *      {@link Constructor#newInstance(Object...) Constructor.newInstance}
 379      *      will throw {@code IllegalAccessException} when it is called on
 380      *      an inaccessible proxy class.
 381      *      Use {@link #newProxyInstance(ClassLoader, Class[], InvocationHandler)}
 382      *      to create a proxy instance instead.
 383      *
 384      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
 385      * @revised 9
 386      */
 387     @Deprecated
 388     @CallerSensitive
 389     public static Class<?> getProxyClass(ClassLoader loader,
 390                                          Class<?>... interfaces)
 391         throws IllegalArgumentException
 392     {
 393         @SuppressWarnings("removal")
 394         Class<?> caller = System.getSecurityManager() == null
 395                               ? null
 396                               : Reflection.getCallerClass();
 397 
 398         return getProxyConstructor(caller, loader, interfaces)
 399             .getDeclaringClass();
 400     }
 401 
 402     /**
 403      * Returns the {@code Constructor} object of a proxy class that takes a
 404      * single argument of type {@link InvocationHandler}, given a class loader
 405      * and an array of interfaces. The returned constructor will have the
 406      * {@link Constructor#setAccessible(boolean) accessible} flag already set.
 407      *
 408      * @param   caller passed from a public-facing @CallerSensitive method if
 409      *                 SecurityManager is set or {@code null} if there's no
 410      *                 SecurityManager
 411      * @param   loader the class loader to define the proxy class
 412      * @param   interfaces the list of interfaces for the proxy class
 413      *          to implement
 414      * @return  a Constructor of the proxy class taking single
 415      *          {@code InvocationHandler} parameter
 416      */
 417     private static Constructor<?> getProxyConstructor(Class<?> caller,
 418                                                       ClassLoader loader,
 419                                                       Class<?>... interfaces)
 420     {
 421         // optimization for single interface
 422         if (interfaces.length == 1) {
 423             Class<?> intf = interfaces[0];
 424             if (caller != null) {
 425                 checkProxyAccess(caller, loader, intf);
 426             }
 427             return proxyCache.sub(intf).computeIfAbsent(
 428                 loader,
 429                 (ld, clv) -> new ProxyBuilder(ld, clv.key()).build()
 430             );
 431         } else {
 432             // interfaces cloned
 433             final Class<?>[] intfsArray = interfaces.clone();
 434             if (caller != null) {
 435                 checkProxyAccess(caller, loader, intfsArray);
 436             }
 437             final List<Class<?>> intfs = Arrays.asList(intfsArray);
 438             return proxyCache.sub(intfs).computeIfAbsent(
 439                 loader,
 440                 (ld, clv) -> new ProxyBuilder(ld, clv.key()).build()
 441             );
 442         }
 443     }
 444 
 445     /*
 446      * Check permissions required to create a Proxy class.
 447      *
 448      * To define a proxy class, it performs the access checks as in
 449      * Class.forName (VM will invoke ClassLoader.checkPackageAccess):
 450      * 1. "getClassLoader" permission check if loader == null
 451      * 2. checkPackageAccess on the interfaces it implements
 452      *
 453      * To get a constructor and new instance of a proxy class, it performs
 454      * the package access check on the interfaces it implements
 455      * as in Class.getConstructor.
 456      *
 457      * If an interface is non-public, the proxy class must be defined by
 458      * the defining loader of the interface.  If the caller's class loader
 459      * is not the same as the defining loader of the interface, the VM
 460      * will throw IllegalAccessError when the generated proxy class is
 461      * being defined.
 462      */
 463     private static void checkProxyAccess(Class<?> caller,
 464                                          ClassLoader loader,
 465                                          Class<?> ... interfaces)
 466     {
 467         @SuppressWarnings("removal")
 468         SecurityManager sm = System.getSecurityManager();
 469         if (sm != null) {
 470             ClassLoader ccl = caller.getClassLoader();
 471             if (loader == null && ccl != null) {
 472                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 473             }
 474             ReflectUtil.checkProxyPackageAccess(ccl, interfaces);
 475         }
 476     }
 477 
 478     /**
 479      * Builder for a proxy class.
 480      *
 481      * If the module is not specified in this ProxyBuilder constructor,
 482      * it will map from the given loader and interfaces to the module
 483      * in which the proxy class will be defined.
 484      */
 485     private static final class ProxyBuilder {
 486         private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
 487 
 488         // prefix for all proxy class names
 489         private static final String proxyClassNamePrefix = "$Proxy";
 490 
 491         // next number to use for generation of unique proxy class names
 492         private static final AtomicLong nextUniqueNumber = new AtomicLong();
 493 
 494         // a reverse cache of defined proxy classes
 495         private static final ClassLoaderValue<Boolean> reverseProxyCache =
 496             new ClassLoaderValue<>();
 497 
 498         private record ProxyClassContext(Module module, String packageName, int accessFlags) {
 499             private ProxyClassContext {
 500                 if (module.isNamed()) {
 501                     if (packageName.isEmpty()) {
 502                         // Per JLS 7.4.2, unnamed package can only exist in unnamed modules.
 503                         // This means a package-private superinterface exist in the unnamed
 504                         // package of a named module.
 505                         throw new InternalError("Unnamed package cannot be added to " + module);
 506                     }
 507 
 508                     if (!module.getDescriptor().packages().contains(packageName)) {
 509                         throw new InternalError(packageName + " not exist in " + module.getName());
 510                     }
 511 
 512                     if (!module.isOpen(packageName, Proxy.class.getModule())) {
 513                         // Required for default method invocation
 514                         throw new InternalError(packageName + " not open to " + Proxy.class.getModule());
 515                     }
 516                 } else {
 517                     if (Modifier.isPublic(accessFlags)) {
 518                         // All proxy superinterfaces are public, must be in named dynamic module
 519                         throw new InternalError("public proxy in unnamed module: " + module);
 520                     }
 521                 }
 522 
 523                 if ((accessFlags & ~Modifier.PUBLIC) != 0) {
 524                     throw new InternalError("proxy access flags must be Modifier.PUBLIC or 0");
 525                 }
 526             }
 527         }
 528 
 529         private static Class<?> defineProxyClass(ProxyClassContext context, List<Class<?>> interfaces) {
 530             /*
 531              * Choose a name for the proxy class to generate.
 532              */
 533             long num = nextUniqueNumber.getAndIncrement();
 534             String proxyName = context.packageName().isEmpty()
 535                                     ? proxyClassNamePrefix + num
 536                                     : context.packageName() + "." + proxyClassNamePrefix + num;
 537 
 538             ClassLoader loader = getLoader(context.module());
 539             trace(proxyName, context.module(), loader, interfaces);
 540 
 541             /*
 542              * Generate the specified proxy class.
 543              */
 544             byte[] proxyClassFile = ProxyGenerator.generateProxyClass(loader, proxyName, interfaces,
 545                                                                       context.accessFlags() | Modifier.FINAL);
 546             try {
 547                 Class<?> pc = JLA.defineClass(loader, proxyName, proxyClassFile,
 548                                               null, "__dynamic_proxy__");
 549                 reverseProxyCache.sub(pc).putIfAbsent(loader, Boolean.TRUE);
 550                 return pc;
 551             } catch (ClassFormatError e) {
 552                 /*
 553                  * A ClassFormatError here means that (barring bugs in the
 554                  * proxy class generation code) there was some other
 555                  * invalid aspect of the arguments supplied to the proxy
 556                  * class creation (such as virtual machine limitations
 557                  * exceeded).
 558                  */
 559                 throw new IllegalArgumentException(e.toString());
 560             }
 561         }
 562 
 563         /**
 564          * Test if given class is a class defined by
 565          * {@link #defineProxyClass(ProxyClassContext, List)}
 566          */
 567         static boolean isProxyClass(Class<?> c) {
 568             return Objects.equals(reverseProxyCache.sub(c).get(c.getClassLoader()),
 569                                   Boolean.TRUE);
 570         }
 571 
 572         private static boolean isExportedType(Class<?> c) {
 573             String pn = c.getPackageName();
 574             return Modifier.isPublic(c.getModifiers()) && c.getModule().isExported(pn);
 575         }
 576 
 577         private static boolean isPackagePrivateType(Class<?> c) {
 578             return !Modifier.isPublic(c.getModifiers());
 579         }
 580 
 581         private static String toDetails(Class<?> c) {
 582             String access = "unknown";
 583             if (isExportedType(c)) {
 584                 access = "exported";
 585             } else if (isPackagePrivateType(c)) {
 586                 access = "package-private";
 587             } else {
 588                 access = "module-private";
 589             }
 590             ClassLoader ld = c.getClassLoader();
 591             return String.format("   %s/%s %s loader %s",
 592                     c.getModule().getName(), c.getName(), access, ld);
 593         }
 594 
 595         static void trace(String cn,
 596                           Module module,
 597                           ClassLoader loader,
 598                           List<Class<?>> interfaces) {
 599             if (isDebug()) {
 600                 System.err.format("PROXY: %s/%s defined by %s%n",
 601                                   module.getName(), cn, loader);
 602             }
 603             if (isDebug("debug")) {
 604                 interfaces.forEach(c -> System.out.println(toDetails(c)));
 605             }
 606         }
 607 
 608         private static final String DEBUG =
 609             GetPropertyAction.privilegedGetProperty("jdk.proxy.debug", "");
 610 
 611         private static boolean isDebug() {
 612             return !DEBUG.isEmpty();
 613         }
 614         private static boolean isDebug(String flag) {
 615             return DEBUG.equals(flag);
 616         }
 617 
 618         // ProxyBuilder instance members start here....
 619 
 620         private final List<Class<?>> interfaces;
 621         private final ProxyClassContext context;
 622         ProxyBuilder(ClassLoader loader, List<Class<?>> interfaces) {
 623             if (!VM.isModuleSystemInited()) {
 624                 throw new InternalError("Proxy is not supported until "
 625                         + "module system is fully initialized");
 626             }
 627             if (interfaces.size() > 65535) {
 628                 throw new IllegalArgumentException("interface limit exceeded: "
 629                         + interfaces.size());
 630             }
 631 
 632             Set<Class<?>> refTypes = referencedTypes(loader, interfaces);
 633 
 634             // IAE if violates any restrictions specified in newProxyInstance
 635             validateProxyInterfaces(loader, interfaces, refTypes);
 636 
 637             this.interfaces = interfaces;
 638             this.context = proxyClassContext(loader, interfaces, refTypes);
 639             assert getLoader(context.module()) == loader;
 640         }
 641 
 642         ProxyBuilder(ClassLoader loader, Class<?> intf) {
 643             this(loader, Collections.singletonList(intf));
 644         }
 645 
 646         /**
 647          * Generate a proxy class and return its proxy Constructor with
 648          * accessible flag already set. If the target module does not have access
 649          * to any interface types, IllegalAccessError will be thrown by the VM
 650          * at defineClass time.
 651          *
 652          * Must call the checkProxyAccess method to perform permission checks
 653          * before calling this.
 654          */
 655         @SuppressWarnings("removal")
 656         Constructor<?> build() {
 657             Class<?> proxyClass = defineProxyClass(context, interfaces);
 658 
 659             final Constructor<?> cons;
 660             try {
 661                 cons = proxyClass.getConstructor(constructorParams);
 662             } catch (NoSuchMethodException e) {
 663                 throw new InternalError(e.toString(), e);
 664             }
 665             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 666                 public Void run() {
 667                     cons.setAccessible(true);
 668                     return null;
 669                 }
 670             });
 671             return cons;
 672         }
 673 
 674         /**
 675          * Validate the given proxy interfaces and the given referenced types
 676          * are visible to the defining loader.
 677          *
 678          * @throws IllegalArgumentException if it violates the restrictions
 679          *         specified in {@link Proxy#newProxyInstance}
 680          */
 681         private static void validateProxyInterfaces(ClassLoader loader,
 682                                                     List<Class<?>> interfaces,
 683                                                     Set<Class<?>> refTypes)
 684         {
 685             Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.size());
 686             for (Class<?> intf : interfaces) {
 687                 /*
 688                  * Verify that the Class object actually represents an
 689                  * interface.
 690                  */
 691                 if (!intf.isInterface()) {
 692                     throw new IllegalArgumentException(intf.getName() + " is not an interface");
 693                 }
 694 
 695                 if (intf.isHidden()) {
 696                     throw new IllegalArgumentException(intf.getName() + " is a hidden interface");
 697                 }
 698 
 699                 if (intf.isSealed()) {
 700                     throw new IllegalArgumentException(intf.getName() + " is a sealed interface");
 701                 }
 702 
 703                 /*
 704                  * Verify that the class loader resolves the name of this
 705                  * interface to the same Class object.
 706                  */
 707                 ensureVisible(loader, intf);
 708 
 709                 /*
 710                  * Verify that this interface is not a duplicate.
 711                  */
 712                 if (interfaceSet.put(intf, Boolean.TRUE) != null) {
 713                     throw new IllegalArgumentException("repeated interface: " + intf.getName());
 714                 }
 715             }
 716 
 717             for (Class<?> type : refTypes) {
 718                 ensureVisible(loader, type);
 719             }
 720         }
 721 
 722         /*
 723          * Returns all types referenced by all public non-static method signatures of
 724          * the proxy interfaces
 725          */
 726         private static Set<Class<?>> referencedTypes(ClassLoader loader,
 727                                                      List<Class<?>> interfaces) {
 728             var types = new HashSet<Class<?>>();
 729             for (var intf : interfaces) {
 730                 for (Method m : intf.getMethods()) {
 731                     if (!Modifier.isStatic(m.getModifiers())) {
 732                         addElementType(types, m.getReturnType());
 733                         addElementTypes(types, m.getSharedParameterTypes());
 734                         addElementTypes(types, m.getSharedExceptionTypes());
 735                     }
 736                 }
 737             }
 738             return types;
 739         }
 740 
 741         private static void addElementTypes(HashSet<Class<?>> types,
 742                                             Class<?> ... classes) {
 743             for (var cls : classes) {
 744                 addElementType(types, cls);
 745             }
 746         }
 747 
 748         private static void addElementType(HashSet<Class<?>> types,
 749                                            Class<?> cls) {
 750             var type = getElementType(cls);
 751             if (!type.isPrimitive()) {
 752                 types.add(type);
 753             }
 754         }
 755 
 756         /**
 757          * Returns the context for the generated proxy class, including the
 758          * module and the package it belongs to and whether it is package-private.
 759          *
 760          * If any of proxy interface is package-private, then the proxy class
 761          * is in the same package and module as the package-private interface.
 762          *
 763          * If all proxy interfaces are public and in exported packages,
 764          * then the proxy class is in a dynamic module in an unconditionally
 765          * exported package.
 766          *
 767          * If all proxy interfaces are public and at least one in a non-exported
 768          * package, then the proxy class is in a dynamic module in a
 769          * non-exported package.
 770          *
 771          * The package of proxy class is open to java.base for deep reflective access.
 772          *
 773          * Reads edge and qualified exports are added for dynamic module to access.
 774          */
 775         private static ProxyClassContext proxyClassContext(ClassLoader loader,
 776                                                            List<Class<?>> interfaces,
 777                                                            Set<Class<?>> refTypes) {
 778             Map<Class<?>, Module> packagePrivateTypes = new HashMap<>();
 779             boolean nonExported = false;
 780 
 781             for (Class<?> intf : interfaces) {
 782                 Module m = intf.getModule();
 783                 if (!Modifier.isPublic(intf.getModifiers())) {
 784                     packagePrivateTypes.put(intf, m);
 785                 } else {
 786                     if (!intf.getModule().isExported(intf.getPackageName())) {
 787                         // module-private types
 788                         nonExported = true;
 789                     }
 790                 }
 791             }
 792 
 793             if (packagePrivateTypes.size() > 0) {
 794                 // all package-private types must be in the same runtime package
 795                 // i.e. same package name and same module (named or unnamed)
 796                 //
 797                 // Configuration will fail if M1 and in M2 defined by the same loader
 798                 // and both have the same package p (so no need to check class loader)
 799                 Module targetModule = null;
 800                 String targetPackageName = null;
 801                 for (Map.Entry<Class<?>, Module> e : packagePrivateTypes.entrySet()) {
 802                     Class<?> intf = e.getKey();
 803                     Module m = e.getValue();
 804                     if ((targetModule != null && targetModule != m) ||
 805                         (targetPackageName != null && targetPackageName != intf.getPackageName())) {
 806                         throw new IllegalArgumentException(
 807                                 "cannot have non-public interfaces in different packages");
 808                     }
 809                     if (getLoader(m) != loader) {
 810                         // the specified loader is not the same class loader
 811                         // of the non-public interface
 812                         throw new IllegalArgumentException(
 813                                 "non-public interface is not defined by the given loader");
 814                     }
 815 
 816                     targetModule = m;
 817                     targetPackageName = e.getKey().getPackageName();
 818                 }
 819 
 820                 // validate if the target module can access all other interfaces
 821                 for (Class<?> intf : interfaces) {
 822                     Module m = intf.getModule();
 823                     if (m == targetModule) continue;
 824 
 825                     if (!targetModule.canRead(m) || !m.isExported(intf.getPackageName(), targetModule)) {
 826                         throw new IllegalArgumentException(targetModule + " can't access " + intf.getName());
 827                     }
 828                 }
 829 
 830                 // opens the package of the non-public proxy class for java.base to access
 831                 if (targetModule.isNamed()) {
 832                     Modules.addOpens(targetModule, targetPackageName, Proxy.class.getModule());
 833                 }
 834                 // return the module of the package-private interface
 835                 return new ProxyClassContext(targetModule, targetPackageName, 0);
 836             }
 837 
 838             // All proxy interfaces are public.  So maps to a dynamic proxy module
 839             // and add reads edge and qualified exports, if necessary
 840             Module targetModule = getDynamicModule(loader);
 841 
 842             // set up proxy class access to proxy interfaces and types
 843             // referenced in the method signature
 844             Set<Class<?>> types = new HashSet<>(interfaces);
 845             types.addAll(refTypes);
 846             for (Class<?> c : types) {
 847                 ensureAccess(targetModule, c);
 848             }
 849 
 850             var pkgName = nonExported ? PROXY_PACKAGE_PREFIX + '.' + targetModule.getName()
 851                                       : targetModule.getName();
 852             return new ProxyClassContext(targetModule, pkgName, Modifier.PUBLIC);
 853         }
 854 
 855         /*
 856          * Ensure the given module can access the given class.
 857          */
 858         private static void ensureAccess(Module target, Class<?> c) {
 859             Module m = c.getModule();
 860             // add read edge and qualified export for the target module to access
 861             if (!target.canRead(m)) {
 862                 Modules.addReads(target, m);
 863             }
 864             String pn = c.getPackageName();
 865             if (!m.isExported(pn, target)) {
 866                 Modules.addExports(m, pn, target);
 867             }
 868         }
 869 
 870         /*
 871          * Ensure the given class is visible to the class loader.
 872          */
 873         private static void ensureVisible(ClassLoader ld, Class<?> c) {
 874             Class<?> type = null;
 875             try {
 876                 type = Class.forName(c.getName(), false, ld);
 877             } catch (ClassNotFoundException e) {
 878             }
 879             if (type != c) {
 880                 throw new IllegalArgumentException(c.getName() +
 881                         " referenced from a method is not visible from class loader");
 882             }
 883         }
 884 
 885         private static Class<?> getElementType(Class<?> type) {
 886             Class<?> e = type;
 887             while (e.isArray()) {
 888                 e = e.getComponentType();
 889             }
 890             return e;
 891         }
 892 
 893         private static final ClassLoaderValue<Module> dynProxyModules =
 894             new ClassLoaderValue<>();
 895         private static final AtomicInteger counter = new AtomicInteger();
 896 
 897         /*
 898          * Define a dynamic module with a package named $MODULE which
 899          * is unconditionally exported and another package named
 900          * com.sun.proxy.$MODULE which is encapsulated.
 901          *
 902          * Each class loader will have one dynamic module.
 903          */
 904         private static Module getDynamicModule(ClassLoader loader) {
 905             return dynProxyModules.computeIfAbsent(loader, (ld, clv) -> {
 906                 // create a dynamic module and setup module access
 907                 String mn = "jdk.proxy" + counter.incrementAndGet();
 908                 String pn = PROXY_PACKAGE_PREFIX + "." + mn;
 909                 ModuleDescriptor descriptor =
 910                         ModuleDescriptor.newModule(mn, Set.of(SYNTHETIC))
 911                                         .packages(Set.of(pn, mn))
 912                                         .exports(mn)
 913                                         .build();
 914                 Module m = Modules.defineModule(ld, descriptor, null);
 915                 Modules.addReads(m, Proxy.class.getModule());
 916                 Modules.addExports(m, mn);
 917                 // java.base to create proxy instance and access its Lookup instance
 918                 Modules.addOpens(m, pn, Proxy.class.getModule());
 919                 Modules.addOpens(m, mn, Proxy.class.getModule());
 920                 return m;
 921             });
 922         }
 923     }
 924 
 925     /**
 926      * Returns a proxy instance for the specified interfaces
 927      * that dispatches method invocations to the specified invocation
 928      * handler.
 929      * <p>
 930      * <a id="restrictions">{@code IllegalArgumentException} will be thrown
 931      * if any of the following restrictions is violated:</a>
 932      * <ul>
 933      * <li>All of {@code Class} objects in the given {@code interfaces} array
 934      * must represent {@linkplain Class#isHidden() non-hidden} and
 935      * {@linkplain Class#isSealed() non-sealed} interfaces,
 936      * not classes or primitive types.
 937      *
 938      * <li>No two elements in the {@code interfaces} array may
 939      * refer to identical {@code Class} objects.
 940      *
 941      * <li>All of the interface types must be visible by name through the
 942      * specified class loader. In other words, for class loader
 943      * {@code cl} and every interface {@code i}, the following
 944      * expression must be true:<p>
 945      * {@code Class.forName(i.getName(), false, cl) == i}
 946      *
 947      * <li>All of the types referenced by all
 948      * public method signatures of the specified interfaces
 949      * and those inherited by their superinterfaces
 950      * must be visible by name through the specified class loader.
 951      *
 952      * <li>All non-public interfaces must be in the same package
 953      * and module, defined by the specified class loader and
 954      * the module of the non-public interfaces can access all of
 955      * the interface types; otherwise, it would not be possible for
 956      * the proxy class to implement all of the interfaces,
 957      * regardless of what package it is defined in.
 958      *
 959      * <li>For any set of member methods of the specified interfaces
 960      * that have the same signature:
 961      * <ul>
 962      * <li>If the return type of any of the methods is a primitive
 963      * type or void, then all of the methods must have that same
 964      * return type.
 965      * <li>Otherwise, one of the methods must have a return type that
 966      * is assignable to all of the return types of the rest of the
 967      * methods.
 968      * </ul>
 969      *
 970      * <li>The resulting proxy class must not exceed any limits imposed
 971      * on classes by the virtual machine.  For example, the VM may limit
 972      * the number of interfaces that a class may implement to 65535; in
 973      * that case, the size of the {@code interfaces} array must not
 974      * exceed 65535.
 975      * </ul>
 976      *
 977      * <p>Note that the order of the specified proxy interfaces is
 978      * significant: two requests for a proxy class with the same combination
 979      * of interfaces but in a different order will result in two distinct
 980      * proxy classes.
 981      *
 982      * @param   loader the class loader to define the proxy class
 983      * @param   interfaces the list of interfaces for the proxy class
 984      *          to implement
 985      * @param   h the invocation handler to dispatch method invocations to
 986      * @return  a proxy instance with the specified invocation handler of a
 987      *          proxy class that is defined by the specified class loader
 988      *          and that implements the specified interfaces
 989      * @throws  IllegalArgumentException if any of the <a href="#restrictions">
 990      *          restrictions</a> on the parameters are violated
 991      * @throws  SecurityException if a security manager, <em>s</em>, is present
 992      *          and any of the following conditions is met:
 993      *          <ul>
 994      *          <li> the given {@code loader} is {@code null} and
 995      *               the caller's class loader is not {@code null} and the
 996      *               invocation of {@link SecurityManager#checkPermission
 997      *               s.checkPermission} with
 998      *               {@code RuntimePermission("getClassLoader")} permission
 999      *               denies access;</li>
1000      *          <li> for each proxy interface, {@code intf},
1001      *               the caller's class loader is not the same as or an
1002      *               ancestor of the class loader for {@code intf} and
1003      *               invocation of {@link SecurityManager#checkPackageAccess
1004      *               s.checkPackageAccess()} denies access to {@code intf};</li>
1005      *          <li> any of the given proxy interfaces is non-public and the
1006      *               caller class is not in the same {@linkplain Package runtime package}
1007      *               as the non-public interface and the invocation of
1008      *               {@link SecurityManager#checkPermission s.checkPermission} with
1009      *               {@code ReflectPermission("newProxyInPackage.{package name}")}
1010      *               permission denies access.</li>
1011      *          </ul>
1012      * @throws  NullPointerException if the {@code interfaces} array
1013      *          argument or any of its elements are {@code null}, or
1014      *          if the invocation handler, {@code h}, is
1015      *          {@code null}
1016      *
1017      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
1018      * @revised 9
1019      */
1020     @CallerSensitive
1021     public static Object newProxyInstance(ClassLoader loader,
1022                                           Class<?>[] interfaces,
1023                                           InvocationHandler h) {
1024         Objects.requireNonNull(h);
1025 
1026         @SuppressWarnings("removal")
1027         final Class<?> caller = System.getSecurityManager() == null
1028                                     ? null
1029                                     : Reflection.getCallerClass();
1030 
1031         /*
1032          * Look up or generate the designated proxy class and its constructor.
1033          */
1034         Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);
1035 
1036         return newProxyInstance(caller, cons, h);
1037     }
1038 
1039     private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager
1040                                            Constructor<?> cons,
1041                                            InvocationHandler h) {
1042         /*
1043          * Invoke its constructor with the designated invocation handler.
1044          */
1045         try {
1046             if (caller != null) {
1047                 checkNewProxyPermission(caller, cons.getDeclaringClass());
1048             }
1049 
1050             return cons.newInstance(new Object[]{h});
1051         } catch (IllegalAccessException | InstantiationException e) {
1052             throw new InternalError(e.toString(), e);
1053         } catch (InvocationTargetException e) {
1054             Throwable t = e.getCause();
1055             if (t instanceof RuntimeException) {
1056                 throw (RuntimeException) t;
1057             } else {
1058                 throw new InternalError(t.toString(), t);
1059             }
1060         }
1061     }
1062 
1063     private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) {
1064         @SuppressWarnings("removal")
1065         SecurityManager sm = System.getSecurityManager();
1066         if (sm != null) {
1067             if (ReflectUtil.isNonPublicProxyClass(proxyClass)) {
1068                 ClassLoader ccl = caller.getClassLoader();
1069                 ClassLoader pcl = proxyClass.getClassLoader();
1070 
1071                 // do permission check if the caller is in a different runtime package
1072                 // of the proxy class
1073                 String pkg = proxyClass.getPackageName();
1074                 String callerPkg = caller.getPackageName();
1075 
1076                 if (pcl != ccl || !pkg.equals(callerPkg)) {
1077                     sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg));
1078                 }
1079             }
1080         }
1081     }
1082 
1083     /**
1084      * Returns the class loader for the given module.
1085      */
1086     @SuppressWarnings("removal")
1087     private static ClassLoader getLoader(Module m) {
1088         PrivilegedAction<ClassLoader> pa = m::getClassLoader;
1089         return AccessController.doPrivileged(pa);
1090     }
1091 
1092     /**
1093      * Returns true if the given class is a proxy class.
1094      *
1095      * @implNote The reliability of this method is important for the ability
1096      * to use it to make security decisions, so its implementation should
1097      * not just test if the class in question extends {@code Proxy}.
1098      *
1099      * @param   cl the class to test
1100      * @return  {@code true} if the class is a proxy class and
1101      *          {@code false} otherwise
1102      * @throws  NullPointerException if {@code cl} is {@code null}
1103      *
1104      * @revised 9
1105      */
1106     public static boolean isProxyClass(Class<?> cl) {
1107         return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl);
1108     }
1109 
1110     /**
1111      * Returns the invocation handler for the specified proxy instance.
1112      *
1113      * @param   proxy the proxy instance to return the invocation handler for
1114      * @return  the invocation handler for the proxy instance
1115      * @throws  IllegalArgumentException if the argument is not a
1116      *          proxy instance
1117      * @throws  SecurityException if a security manager, <em>s</em>, is present
1118      *          and the caller's class loader is not the same as or an
1119      *          ancestor of the class loader for the invocation handler
1120      *          and invocation of {@link SecurityManager#checkPackageAccess
1121      *          s.checkPackageAccess()} denies access to the invocation
1122      *          handler's class.
1123      */
1124     @SuppressWarnings("removal")
1125     @CallerSensitive
1126     public static InvocationHandler getInvocationHandler(Object proxy)
1127         throws IllegalArgumentException
1128     {
1129         /*
1130          * Verify that the object is actually a proxy instance.
1131          */
1132         if (!isProxyClass(proxy.getClass())) {
1133             throw new IllegalArgumentException("not a proxy instance");
1134         }
1135 
1136         final Proxy p = (Proxy) proxy;
1137         final InvocationHandler ih = p.h;
1138         if (System.getSecurityManager() != null) {
1139             Class<?> ihClass = ih.getClass();
1140             Class<?> caller = Reflection.getCallerClass();
1141             if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
1142                                                     ihClass.getClassLoader()))
1143             {
1144                 ReflectUtil.checkPackageAccess(ihClass);
1145             }
1146         }
1147 
1148         return ih;
1149     }
1150 
1151     private static final String PROXY_PACKAGE_PREFIX = ReflectUtil.PROXY_PACKAGE;
1152 
1153     /**
1154      * A cache of Method -> MethodHandle for default methods.
1155      */
1156     private static final ClassValue<ConcurrentHashMap<Method, MethodHandle>>
1157             DEFAULT_METHODS_MAP = new ClassValue<>() {
1158         @Override
1159         protected ConcurrentHashMap<Method, MethodHandle> computeValue(Class<?> type) {
1160             return new ConcurrentHashMap<>(4);
1161         }
1162     };
1163 
1164     private static ConcurrentHashMap<Method, MethodHandle> defaultMethodMap(Class<?> proxyClass) {
1165         assert isProxyClass(proxyClass);
1166         return DEFAULT_METHODS_MAP.get(proxyClass);
1167     }
1168 
1169     static final Object[] EMPTY_ARGS = new Object[0];
1170 
1171     static MethodHandle defaultMethodHandle(Class<? extends Proxy> proxyClass, Method method) {
1172         // lookup the cached method handle
1173         ConcurrentHashMap<Method, MethodHandle> methods = defaultMethodMap(proxyClass);
1174         MethodHandle superMH = methods.get(method);
1175         if (superMH == null) {
1176             MethodType type = methodType(method.getReturnType(), method.getParameterTypes());
1177             MethodHandles.Lookup lookup = MethodHandles.lookup();
1178             Class<?> proxyInterface = findProxyInterfaceOrElseThrow(proxyClass, method);
1179             MethodHandle dmh;
1180             try {
1181                 dmh = proxyClassLookup(lookup, proxyClass)
1182                         .findSpecial(proxyInterface, method.getName(), type, proxyClass)
1183                         .withVarargs(false);
1184             } catch (IllegalAccessException | NoSuchMethodException e) {
1185                 // should not reach here
1186                 throw new InternalError(e);
1187             }
1188             // this check can be turned into assertion as it is guaranteed to succeed by the virtue of
1189             // looking up a default (instance) method declared or inherited by proxyInterface
1190             // while proxyClass implements (is a subtype of) proxyInterface ...
1191             assert ((BooleanSupplier) () -> {
1192                 try {
1193                     // make sure that the method type matches
1194                     dmh.asType(type.insertParameterTypes(0, proxyClass));
1195                     return true;
1196                 } catch (WrongMethodTypeException e) {
1197                     return false;
1198                 }
1199             }).getAsBoolean() : "Wrong method type";
1200             // change return type to Object
1201             MethodHandle mh = dmh.asType(dmh.type().changeReturnType(Object.class));
1202             // wrap any exception thrown with InvocationTargetException
1203             mh = MethodHandles.catchException(mh, Throwable.class, InvocationException.wrapMH());
1204             // spread array of arguments among parameters (skipping 1st parameter - target)
1205             mh = mh.asSpreader(1, Object[].class, type.parameterCount());
1206             // change target type to Object
1207             mh = mh.asType(MethodType.methodType(Object.class, Object.class, Object[].class));
1208 
1209             // push MH into cache
1210             MethodHandle cached = methods.putIfAbsent(method, mh);
1211             if (cached != null) {
1212                 superMH = cached;
1213             } else {
1214                 superMH = mh;
1215             }
1216         }
1217         return superMH;
1218     }
1219 
1220     /**
1221      * Finds the first proxy interface that declares the given method
1222      * directly or indirectly.
1223      *
1224      * @throws IllegalArgumentException if not found
1225      */
1226     private static Class<?> findProxyInterfaceOrElseThrow(Class<?> proxyClass, Method method) {
1227         Class<?> declaringClass = method.getDeclaringClass();
1228         if (!declaringClass.isInterface()) {
1229             throw new IllegalArgumentException("\"" + method +
1230                     "\" is not a method declared in the proxy class");
1231         }
1232 
1233         List<Class<?>> proxyInterfaces = Arrays.asList(proxyClass.getInterfaces());
1234         // the method's declaring class is a proxy interface
1235         if (proxyInterfaces.contains(declaringClass))
1236             return declaringClass;
1237 
1238         // find the first proxy interface that inherits the default method
1239         // i.e. the declaring class of the default method is a superinterface
1240         // of the proxy interface
1241         Deque<Class<?>> deque = new ArrayDeque<>();
1242         Set<Class<?>> visited = new HashSet<>();
1243         boolean indirectMethodRef = false;
1244         for (Class<?> proxyIntf : proxyInterfaces) {
1245             assert proxyIntf != declaringClass;
1246             visited.add(proxyIntf);
1247             deque.add(proxyIntf);
1248 
1249             // for each proxy interface, traverse its subinterfaces with
1250             // breadth-first search to find a subinterface declaring the
1251             // default method
1252             Class<?> c;
1253             while ((c = deque.poll()) != null) {
1254                 if (c == declaringClass) {
1255                     try {
1256                         // check if this method is the resolved method if referenced from
1257                         // this proxy interface (i.e. this method is not implemented
1258                         // by any other superinterface)
1259                         Method m = proxyIntf.getMethod(method.getName(), method.getSharedParameterTypes());
1260                         if (m.getDeclaringClass() == declaringClass) {
1261                             return proxyIntf;
1262                         }
1263                         indirectMethodRef = true;
1264                     } catch (NoSuchMethodException e) {}
1265 
1266                     // skip traversing its superinterfaces
1267                     // another proxy interface may extend it and so
1268                     // the method's declaring class is left unvisited.
1269                     continue;
1270                 }
1271                 // visit all superinteraces of one proxy interface to find if
1272                 // this proxy interface inherits the method directly or indirectly
1273                 visited.add(c);
1274                 for (Class<?> superIntf : c.getInterfaces()) {
1275                     if (!visited.contains(superIntf) && !deque.contains(superIntf)) {
1276                         if (superIntf == declaringClass) {
1277                             // fast-path as the matching subinterface is found
1278                             deque.addFirst(superIntf);
1279                         } else {
1280                             deque.add(superIntf);
1281                         }
1282                     }
1283                 }
1284             }
1285         }
1286 
1287         throw new IllegalArgumentException("\"" + method + (indirectMethodRef
1288                 ? "\" is overridden directly or indirectly by the proxy interfaces"
1289                 : "\" is not a method declared in the proxy class"));
1290     }
1291 
1292     /**
1293      * This method invokes the proxy's proxyClassLookup method to get a
1294      * Lookup on the proxy class.
1295      *
1296      * @return a lookup for proxy class of this proxy instance
1297      */
1298     @SuppressWarnings("removal")
1299     private static MethodHandles.Lookup proxyClassLookup(MethodHandles.Lookup caller, Class<?> proxyClass) {
1300         return AccessController.doPrivileged(new PrivilegedAction<>() {
1301             @Override
1302             public MethodHandles.Lookup run() {
1303                 try {
1304                     Method m = proxyClass.getDeclaredMethod("proxyClassLookup", MethodHandles.Lookup.class);
1305                     m.setAccessible(true);
1306                     return (MethodHandles.Lookup) m.invoke(null, caller);
1307                 } catch (ReflectiveOperationException e) {
1308                     throw new InternalError(e);
1309                 }
1310             }
1311         });
1312     }
1313 
1314     /*
1315      * Invoke the default method of the given proxy with an explicit caller class.
1316      *
1317      * @throws IllegalAccessException if the proxy interface is inaccessible to the caller
1318      *         if caller is non-null
1319      */
1320     static Object invokeDefault(Object proxy, Method method, Object[] args, Class<?> caller)
1321             throws Throwable {
1322         // verify that the object is actually a proxy instance
1323         if (!Proxy.isProxyClass(proxy.getClass())) {
1324             throw new IllegalArgumentException("'proxy' is not a proxy instance");
1325         }
1326         if (!method.isDefault()) {
1327             throw new IllegalArgumentException("\"" + method + "\" is not a default method");
1328         }
1329         @SuppressWarnings("unchecked")
1330         Class<? extends Proxy> proxyClass = (Class<? extends Proxy>)proxy.getClass();
1331 
1332         // skip access check if caller is null
1333         if (caller != null) {
1334             Class<?> intf = method.getDeclaringClass();
1335             // access check on the default method
1336             method.checkAccess(caller, intf, proxyClass, method.getModifiers());
1337         }
1338 
1339         MethodHandle mh = Proxy.defaultMethodHandle(proxyClass, method);
1340         // invoke the super method
1341         try {
1342             // the args array can be null if the number of formal parameters required by
1343             // the method is zero (consistent with Method::invoke)
1344             Object[] params = args != null ? args : Proxy.EMPTY_ARGS;
1345             return mh.invokeExact(proxy, params);
1346         } catch (ClassCastException | NullPointerException e) {
1347             throw new IllegalArgumentException(e.getMessage(), e);
1348         } catch (Proxy.InvocationException e) {
1349             // unwrap and throw the exception thrown by the default method
1350             throw e.getCause();
1351         }
1352     }
1353 
1354     /**
1355      * Internal exception type to wrap the exception thrown by the default method
1356      * so that it can distinguish CCE and NPE thrown due to the arguments
1357      * incompatible with the method signature.
1358      */
1359     static class InvocationException extends ReflectiveOperationException {
1360         @java.io.Serial
1361         private static final long serialVersionUID = 0L;
1362 
1363         InvocationException(Throwable cause) {
1364             super(cause);
1365         }
1366 
1367         /**
1368          * Wraps given cause with InvocationException and throws it.
1369          */
1370         static Object wrap(Throwable cause) throws InvocationException {
1371             throw new InvocationException(cause);
1372         }
1373 
1374         @Stable
1375         static MethodHandle wrapMethodHandle;
1376 
1377         static MethodHandle wrapMH() {
1378             MethodHandle mh = wrapMethodHandle;
1379             if (mh == null) {
1380                 try {
1381                     wrapMethodHandle = mh = MethodHandles.lookup().findStatic(
1382                             InvocationException.class,
1383                             "wrap",
1384                             MethodType.methodType(Object.class, Throwable.class)
1385                     );
1386                 } catch (NoSuchMethodException | IllegalAccessException e) {
1387                     throw new InternalError(e);
1388                 }
1389             }
1390             return mh;
1391         }
1392     }
1393 
1394 }