1 /* 2 * Copyright (c) 1999, 2021, 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 static Class<?> defineProxyClass(Module m, List<Class<?>> interfaces) { 499 String proxyPkg = null; // package to define proxy class in 500 int accessFlags = Modifier.PUBLIC | Modifier.FINAL; 501 boolean nonExported = false; 502 503 /* 504 * Record the package of a non-public proxy interface so that the 505 * proxy class will be defined in the same package. Verify that 506 * all non-public proxy interfaces are in the same package. 507 */ 508 for (Class<?> intf : interfaces) { 509 int flags = intf.getModifiers(); 510 if (!Modifier.isPublic(flags)) { 511 accessFlags = Modifier.FINAL; // non-public, final 512 String pkg = intf.getPackageName(); 513 if (proxyPkg == null) { 514 proxyPkg = pkg; 515 } else if (!pkg.equals(proxyPkg)) { 516 throw new IllegalArgumentException( 517 "non-public interfaces from different packages"); 518 } 519 } else { 520 if (!intf.getModule().isExported(intf.getPackageName())) { 521 // module-private types 522 nonExported = true; 523 } 524 } 525 } 526 527 if (proxyPkg == null) { 528 // all proxy interfaces are public and exported 529 if (!m.isNamed()) 530 throw new InternalError("unnamed module: " + m); 531 proxyPkg = nonExported ? PROXY_PACKAGE_PREFIX + "." + m.getName() 532 : m.getName(); 533 } else if (proxyPkg.isEmpty() && m.isNamed()) { 534 throw new IllegalArgumentException( 535 "Unnamed package cannot be added to " + m); 536 } 537 538 if (m.isNamed()) { 539 if (!m.getDescriptor().packages().contains(proxyPkg)) { 540 throw new InternalError(proxyPkg + " not exist in " + m.getName()); 541 } 542 } 543 544 /* 545 * Choose a name for the proxy class to generate. 546 */ 547 long num = nextUniqueNumber.getAndIncrement(); 548 String proxyName = proxyPkg.isEmpty() 549 ? proxyClassNamePrefix + num 550 : proxyPkg + "." + proxyClassNamePrefix + num; 551 552 ClassLoader loader = getLoader(m); 553 trace(proxyName, m, loader, interfaces); 554 555 /* 556 * Generate the specified proxy class. 557 */ 558 byte[] proxyClassFile = ProxyGenerator.generateProxyClass(loader, proxyName, interfaces, accessFlags); 559 try { 560 Class<?> pc = JLA.defineClass(loader, proxyName, proxyClassFile, 561 null, "__dynamic_proxy__"); 562 reverseProxyCache.sub(pc).putIfAbsent(loader, Boolean.TRUE); 563 return pc; 564 } catch (ClassFormatError e) { 565 /* 566 * A ClassFormatError here means that (barring bugs in the 567 * proxy class generation code) there was some other 568 * invalid aspect of the arguments supplied to the proxy 569 * class creation (such as virtual machine limitations 570 * exceeded). 571 */ 572 throw new IllegalArgumentException(e.toString()); 573 } 574 } 575 576 /** 577 * Test if given class is a class defined by 578 * {@link #defineProxyClass(Module, List)} 579 */ 580 static boolean isProxyClass(Class<?> c) { 581 return Objects.equals(reverseProxyCache.sub(c).get(c.getClassLoader()), 582 Boolean.TRUE); 583 } 584 585 private static boolean isExportedType(Class<?> c) { 586 String pn = c.getPackageName(); 587 return Modifier.isPublic(c.getModifiers()) && c.getModule().isExported(pn); 588 } 589 590 private static boolean isPackagePrivateType(Class<?> c) { 591 return !Modifier.isPublic(c.getModifiers()); 592 } 593 594 private static String toDetails(Class<?> c) { 595 String access = "unknown"; 596 if (isExportedType(c)) { 597 access = "exported"; 598 } else if (isPackagePrivateType(c)) { 599 access = "package-private"; 600 } else { 601 access = "module-private"; 602 } 603 ClassLoader ld = c.getClassLoader(); 604 return String.format(" %s/%s %s loader %s", 605 c.getModule().getName(), c.getName(), access, ld); 606 } 607 608 static void trace(String cn, 609 Module module, 610 ClassLoader loader, 611 List<Class<?>> interfaces) { 612 if (isDebug()) { 613 System.err.format("PROXY: %s/%s defined by %s%n", 614 module.getName(), cn, loader); 615 } 616 if (isDebug("debug")) { 617 interfaces.forEach(c -> System.out.println(toDetails(c))); 618 } 619 } 620 621 private static final String DEBUG = 622 GetPropertyAction.privilegedGetProperty("jdk.proxy.debug", ""); 623 624 private static boolean isDebug() { 625 return !DEBUG.isEmpty(); 626 } 627 private static boolean isDebug(String flag) { 628 return DEBUG.equals(flag); 629 } 630 631 // ProxyBuilder instance members start here.... 632 633 private final List<Class<?>> interfaces; 634 private final Module module; 635 ProxyBuilder(ClassLoader loader, List<Class<?>> interfaces) { 636 if (!VM.isModuleSystemInited()) { 637 throw new InternalError("Proxy is not supported until " 638 + "module system is fully initialized"); 639 } 640 if (interfaces.size() > 65535) { 641 throw new IllegalArgumentException("interface limit exceeded: " 642 + interfaces.size()); 643 } 644 645 Set<Class<?>> refTypes = referencedTypes(loader, interfaces); 646 647 // IAE if violates any restrictions specified in newProxyInstance 648 validateProxyInterfaces(loader, interfaces, refTypes); 649 650 this.interfaces = interfaces; 651 this.module = mapToModule(loader, interfaces, refTypes); 652 assert getLoader(module) == loader; 653 } 654 655 ProxyBuilder(ClassLoader loader, Class<?> intf) { 656 this(loader, Collections.singletonList(intf)); 657 } 658 659 /** 660 * Generate a proxy class and return its proxy Constructor with 661 * accessible flag already set. If the target module does not have access 662 * to any interface types, IllegalAccessError will be thrown by the VM 663 * at defineClass time. 664 * 665 * Must call the checkProxyAccess method to perform permission checks 666 * before calling this. 667 */ 668 @SuppressWarnings("removal") 669 Constructor<?> build() { 670 Class<?> proxyClass = defineProxyClass(module, interfaces); 671 assert !module.isNamed() || module.isOpen(proxyClass.getPackageName(), Proxy.class.getModule()); 672 673 final Constructor<?> cons; 674 try { 675 cons = proxyClass.getConstructor(constructorParams); 676 } catch (NoSuchMethodException e) { 677 throw new InternalError(e.toString(), e); 678 } 679 AccessController.doPrivileged(new PrivilegedAction<Void>() { 680 public Void run() { 681 cons.setAccessible(true); 682 return null; 683 } 684 }); 685 return cons; 686 } 687 688 /** 689 * Validate the given proxy interfaces and the given referenced types 690 * are visible to the defining loader. 691 * 692 * @throws IllegalArgumentException if it violates the restrictions 693 * specified in {@link Proxy#newProxyInstance} 694 */ 695 private static void validateProxyInterfaces(ClassLoader loader, 696 List<Class<?>> interfaces, 697 Set<Class<?>> refTypes) 698 { 699 Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.size()); 700 for (Class<?> intf : interfaces) { 701 /* 702 * Verify that the Class object actually represents an 703 * interface. 704 */ 705 if (!intf.isInterface()) { 706 throw new IllegalArgumentException(intf.getName() + " is not an interface"); 707 } 708 709 if (intf.isHidden()) { 710 throw new IllegalArgumentException(intf.getName() + " is a hidden interface"); 711 } 712 713 if (intf.isSealed()) { 714 throw new IllegalArgumentException(intf.getName() + " is a sealed interface"); 715 } 716 717 /* 718 * Verify that the class loader resolves the name of this 719 * interface to the same Class object. 720 */ 721 ensureVisible(loader, intf); 722 723 /* 724 * Verify that this interface is not a duplicate. 725 */ 726 if (interfaceSet.put(intf, Boolean.TRUE) != null) { 727 throw new IllegalArgumentException("repeated interface: " + intf.getName()); 728 } 729 } 730 731 for (Class<?> type : refTypes) { 732 ensureVisible(loader, type); 733 } 734 } 735 736 /* 737 * Returns all types referenced by all public non-static method signatures of 738 * the proxy interfaces 739 */ 740 private static Set<Class<?>> referencedTypes(ClassLoader loader, 741 List<Class<?>> interfaces) { 742 var types = new HashSet<Class<?>>(); 743 for (var intf : interfaces) { 744 for (Method m : intf.getMethods()) { 745 if (!Modifier.isStatic(m.getModifiers())) { 746 addElementType(types, m.getReturnType()); 747 addElementTypes(types, m.getSharedParameterTypes()); 748 addElementTypes(types, m.getSharedExceptionTypes()); 749 } 750 } 751 } 752 return types; 753 } 754 755 private static void addElementTypes(HashSet<Class<?>> types, 756 Class<?> ... classes) { 757 for (var cls : classes) { 758 addElementType(types, cls); 759 } 760 } 761 762 private static void addElementType(HashSet<Class<?>> types, 763 Class<?> cls) { 764 var type = getElementType(cls); 765 if (!type.isPrimitive()) { 766 types.add(type); 767 } 768 } 769 770 /** 771 * Returns the module that the generated proxy class belongs to. 772 * 773 * If any of proxy interface is package-private, then the proxy class 774 * is in the same module of the package-private interface. 775 * 776 * If all proxy interfaces are public and in exported packages, 777 * then the proxy class is in a dynamic module in an unconditionally 778 * exported package. 779 * 780 * If all proxy interfaces are public and at least one in a non-exported 781 * package, then the proxy class is in a dynamic module in a 782 * non-exported package. 783 * 784 * The package of proxy class is open to java.base for deep reflective access. 785 * 786 * Reads edge and qualified exports are added for dynamic module to access. 787 */ 788 private static Module mapToModule(ClassLoader loader, 789 List<Class<?>> interfaces, 790 Set<Class<?>> refTypes) { 791 Map<Class<?>, Module> packagePrivateTypes = new HashMap<>(); 792 for (Class<?> intf : interfaces) { 793 Module m = intf.getModule(); 794 if (!Modifier.isPublic(intf.getModifiers())) { 795 packagePrivateTypes.put(intf, m); 796 } 797 } 798 799 if (packagePrivateTypes.size() > 0) { 800 // all package-private types must be in the same runtime package 801 // i.e. same package name and same module (named or unnamed) 802 // 803 // Configuration will fail if M1 and in M2 defined by the same loader 804 // and both have the same package p (so no need to check class loader) 805 Module targetModule = null; 806 String targetPackageName = null; 807 for (Map.Entry<Class<?>, Module> e : packagePrivateTypes.entrySet()) { 808 Class<?> intf = e.getKey(); 809 Module m = e.getValue(); 810 if ((targetModule != null && targetModule != m) || 811 (targetPackageName != null && targetPackageName != intf.getPackageName())) { 812 throw new IllegalArgumentException( 813 "cannot have non-public interfaces in different packages"); 814 } 815 if (getLoader(m) != loader) { 816 // the specified loader is not the same class loader 817 // of the non-public interface 818 throw new IllegalArgumentException( 819 "non-public interface is not defined by the given loader"); 820 } 821 822 targetModule = m; 823 targetPackageName = e.getKey().getPackageName(); 824 } 825 826 // validate if the target module can access all other interfaces 827 for (Class<?> intf : interfaces) { 828 Module m = intf.getModule(); 829 if (m == targetModule) continue; 830 831 if (!targetModule.canRead(m) || !m.isExported(intf.getPackageName(), targetModule)) { 832 throw new IllegalArgumentException(targetModule + " can't access " + intf.getName()); 833 } 834 } 835 836 // opens the package of the non-public proxy class for java.base to access 837 if (targetModule.isNamed()) { 838 Modules.addOpens(targetModule, targetPackageName, Proxy.class.getModule()); 839 } 840 // return the module of the package-private interface 841 return targetModule; 842 } 843 844 // All proxy interfaces are public. So maps to a dynamic proxy module 845 // and add reads edge and qualified exports, if necessary 846 Module targetModule = getDynamicModule(loader); 847 848 // set up proxy class access to proxy interfaces and types 849 // referenced in the method signature 850 Set<Class<?>> types = new HashSet<>(interfaces); 851 types.addAll(refTypes); 852 for (Class<?> c : types) { 853 ensureAccess(targetModule, c); 854 } 855 return targetModule; 856 } 857 858 /* 859 * Ensure the given module can access the given class. 860 */ 861 private static void ensureAccess(Module target, Class<?> c) { 862 Module m = c.getModule(); 863 // add read edge and qualified export for the target module to access 864 if (!target.canRead(m)) { 865 Modules.addReads(target, m); 866 } 867 String pn = c.getPackageName(); 868 if (!m.isExported(pn, target)) { 869 Modules.addExports(m, pn, target); 870 } 871 } 872 873 /* 874 * Ensure the given class is visible to the class loader. 875 */ 876 private static void ensureVisible(ClassLoader ld, Class<?> c) { 877 Class<?> type = null; 878 try { 879 type = Class.forName(c.getName(), false, ld); 880 } catch (ClassNotFoundException e) { 881 } 882 if (type != c) { 883 throw new IllegalArgumentException(c.getName() + 884 " referenced from a method is not visible from class loader"); 885 } 886 } 887 888 private static Class<?> getElementType(Class<?> type) { 889 Class<?> e = type; 890 while (e.isArray()) { 891 e = e.getComponentType(); 892 } 893 return e; 894 } 895 896 private static final ClassLoaderValue<Module> dynProxyModules = 897 new ClassLoaderValue<>(); 898 private static final AtomicInteger counter = new AtomicInteger(); 899 900 /* 901 * Define a dynamic module with a packge named $MODULE which 902 * is unconditionally exported and another package named 903 * com.sun.proxy.$MODULE which is encapsulated. 904 * 905 * Each class loader will have one dynamic module. 906 */ 907 private static Module getDynamicModule(ClassLoader loader) { 908 return dynProxyModules.computeIfAbsent(loader, (ld, clv) -> { 909 // create a dynamic module and setup module access 910 String mn = "jdk.proxy" + counter.incrementAndGet(); 911 String pn = PROXY_PACKAGE_PREFIX + "." + mn; 912 ModuleDescriptor descriptor = 913 ModuleDescriptor.newModule(mn, Set.of(SYNTHETIC)) 914 .packages(Set.of(pn, mn)) 915 .exports(mn) 916 .build(); 917 Module m = Modules.defineModule(ld, descriptor, null); 918 Modules.addReads(m, Proxy.class.getModule()); 919 Modules.addExports(m, mn); 920 // java.base to create proxy instance and access its Lookup instance 921 Modules.addOpens(m, pn, Proxy.class.getModule()); 922 Modules.addOpens(m, mn, Proxy.class.getModule()); 923 return m; 924 }); 925 } 926 } 927 928 /** 929 * Returns a proxy instance for the specified interfaces 930 * that dispatches method invocations to the specified invocation 931 * handler. 932 * <p> 933 * <a id="restrictions">{@code IllegalArgumentException} will be thrown 934 * if any of the following restrictions is violated:</a> 935 * <ul> 936 * <li>All of {@code Class} objects in the given {@code interfaces} array 937 * must represent {@linkplain Class#isHidden() non-hidden} and 938 * {@linkplain Class#isSealed() non-sealed} interfaces, 939 * not classes or primitive types. 940 * 941 * <li>No two elements in the {@code interfaces} array may 942 * refer to identical {@code Class} objects. 943 * 944 * <li>All of the interface types must be visible by name through the 945 * specified class loader. In other words, for class loader 946 * {@code cl} and every interface {@code i}, the following 947 * expression must be true:<p> 948 * {@code Class.forName(i.getName(), false, cl) == i} 949 * 950 * <li>All of the types referenced by all 951 * public method signatures of the specified interfaces 952 * and those inherited by their superinterfaces 953 * must be visible by name through the specified class loader. 954 * 955 * <li>All non-public interfaces must be in the same package 956 * and module, defined by the specified class loader and 957 * the module of the non-public interfaces can access all of 958 * the interface types; otherwise, it would not be possible for 959 * the proxy class to implement all of the interfaces, 960 * regardless of what package it is defined in. 961 * 962 * <li>For any set of member methods of the specified interfaces 963 * that have the same signature: 964 * <ul> 965 * <li>If the return type of any of the methods is a primitive 966 * type or void, then all of the methods must have that same 967 * return type. 968 * <li>Otherwise, one of the methods must have a return type that 969 * is assignable to all of the return types of the rest of the 970 * methods. 971 * </ul> 972 * 973 * <li>The resulting proxy class must not exceed any limits imposed 974 * on classes by the virtual machine. For example, the VM may limit 975 * the number of interfaces that a class may implement to 65535; in 976 * that case, the size of the {@code interfaces} array must not 977 * exceed 65535. 978 * </ul> 979 * 980 * <p>Note that the order of the specified proxy interfaces is 981 * significant: two requests for a proxy class with the same combination 982 * of interfaces but in a different order will result in two distinct 983 * proxy classes. 984 * 985 * @param loader the class loader to define the proxy class 986 * @param interfaces the list of interfaces for the proxy class 987 * to implement 988 * @param h the invocation handler to dispatch method invocations to 989 * @return a proxy instance with the specified invocation handler of a 990 * proxy class that is defined by the specified class loader 991 * and that implements the specified interfaces 992 * @throws IllegalArgumentException if any of the <a href="#restrictions"> 993 * restrictions</a> on the parameters are violated 994 * @throws SecurityException if a security manager, <em>s</em>, is present 995 * and any of the following conditions is met: 996 * <ul> 997 * <li> the given {@code loader} is {@code null} and 998 * the caller's class loader is not {@code null} and the 999 * invocation of {@link SecurityManager#checkPermission 1000 * s.checkPermission} with 1001 * {@code RuntimePermission("getClassLoader")} permission 1002 * denies access;</li> 1003 * <li> for each proxy interface, {@code intf}, 1004 * the caller's class loader is not the same as or an 1005 * ancestor of the class loader for {@code intf} and 1006 * invocation of {@link SecurityManager#checkPackageAccess 1007 * s.checkPackageAccess()} denies access to {@code intf};</li> 1008 * <li> any of the given proxy interfaces is non-public and the 1009 * caller class is not in the same {@linkplain Package runtime package} 1010 * as the non-public interface and the invocation of 1011 * {@link SecurityManager#checkPermission s.checkPermission} with 1012 * {@code ReflectPermission("newProxyInPackage.{package name}")} 1013 * permission denies access.</li> 1014 * </ul> 1015 * @throws NullPointerException if the {@code interfaces} array 1016 * argument or any of its elements are {@code null}, or 1017 * if the invocation handler, {@code h}, is 1018 * {@code null} 1019 * 1020 * @see <a href="#membership">Package and Module Membership of Proxy Class</a> 1021 * @revised 9 1022 */ 1023 @CallerSensitive 1024 public static Object newProxyInstance(ClassLoader loader, 1025 Class<?>[] interfaces, 1026 InvocationHandler h) { 1027 Objects.requireNonNull(h); 1028 1029 @SuppressWarnings("removal") 1030 final Class<?> caller = System.getSecurityManager() == null 1031 ? null 1032 : Reflection.getCallerClass(); 1033 1034 /* 1035 * Look up or generate the designated proxy class and its constructor. 1036 */ 1037 Constructor<?> cons = getProxyConstructor(caller, loader, interfaces); 1038 1039 return newProxyInstance(caller, cons, h); 1040 } 1041 1042 private static Object newProxyInstance(Class<?> caller, // null if no SecurityManager 1043 Constructor<?> cons, 1044 InvocationHandler h) { 1045 /* 1046 * Invoke its constructor with the designated invocation handler. 1047 */ 1048 try { 1049 if (caller != null) { 1050 checkNewProxyPermission(caller, cons.getDeclaringClass()); 1051 } 1052 1053 return cons.newInstance(new Object[]{h}); 1054 } catch (IllegalAccessException | InstantiationException e) { 1055 throw new InternalError(e.toString(), e); 1056 } catch (InvocationTargetException e) { 1057 Throwable t = e.getCause(); 1058 if (t instanceof RuntimeException) { 1059 throw (RuntimeException) t; 1060 } else { 1061 throw new InternalError(t.toString(), t); 1062 } 1063 } 1064 } 1065 1066 private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) { 1067 @SuppressWarnings("removal") 1068 SecurityManager sm = System.getSecurityManager(); 1069 if (sm != null) { 1070 if (ReflectUtil.isNonPublicProxyClass(proxyClass)) { 1071 ClassLoader ccl = caller.getClassLoader(); 1072 ClassLoader pcl = proxyClass.getClassLoader(); 1073 1074 // do permission check if the caller is in a different runtime package 1075 // of the proxy class 1076 String pkg = proxyClass.getPackageName(); 1077 String callerPkg = caller.getPackageName(); 1078 1079 if (pcl != ccl || !pkg.equals(callerPkg)) { 1080 sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg)); 1081 } 1082 } 1083 } 1084 } 1085 1086 /** 1087 * Returns the class loader for the given module. 1088 */ 1089 @SuppressWarnings("removal") 1090 private static ClassLoader getLoader(Module m) { 1091 PrivilegedAction<ClassLoader> pa = m::getClassLoader; 1092 return AccessController.doPrivileged(pa); 1093 } 1094 1095 /** 1096 * Returns true if the given class is a proxy class. 1097 * 1098 * @implNote The reliability of this method is important for the ability 1099 * to use it to make security decisions, so its implementation should 1100 * not just test if the class in question extends {@code Proxy}. 1101 * 1102 * @param cl the class to test 1103 * @return {@code true} if the class is a proxy class and 1104 * {@code false} otherwise 1105 * @throws NullPointerException if {@code cl} is {@code null} 1106 * 1107 * @revised 9 1108 */ 1109 public static boolean isProxyClass(Class<?> cl) { 1110 return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl); 1111 } 1112 1113 /** 1114 * Returns the invocation handler for the specified proxy instance. 1115 * 1116 * @param proxy the proxy instance to return the invocation handler for 1117 * @return the invocation handler for the proxy instance 1118 * @throws IllegalArgumentException if the argument is not a 1119 * proxy instance 1120 * @throws SecurityException if a security manager, <em>s</em>, is present 1121 * and the caller's class loader is not the same as or an 1122 * ancestor of the class loader for the invocation handler 1123 * and invocation of {@link SecurityManager#checkPackageAccess 1124 * s.checkPackageAccess()} denies access to the invocation 1125 * handler's class. 1126 */ 1127 @SuppressWarnings("removal") 1128 @CallerSensitive 1129 public static InvocationHandler getInvocationHandler(Object proxy) 1130 throws IllegalArgumentException 1131 { 1132 /* 1133 * Verify that the object is actually a proxy instance. 1134 */ 1135 if (!isProxyClass(proxy.getClass())) { 1136 throw new IllegalArgumentException("not a proxy instance"); 1137 } 1138 1139 final Proxy p = (Proxy) proxy; 1140 final InvocationHandler ih = p.h; 1141 if (System.getSecurityManager() != null) { 1142 Class<?> ihClass = ih.getClass(); 1143 Class<?> caller = Reflection.getCallerClass(); 1144 if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), 1145 ihClass.getClassLoader())) 1146 { 1147 ReflectUtil.checkPackageAccess(ihClass); 1148 } 1149 } 1150 1151 return ih; 1152 } 1153 1154 private static final String PROXY_PACKAGE_PREFIX = ReflectUtil.PROXY_PACKAGE; 1155 1156 /** 1157 * A cache of Method -> MethodHandle for default methods. 1158 */ 1159 private static final ClassValue<ConcurrentHashMap<Method, MethodHandle>> 1160 DEFAULT_METHODS_MAP = new ClassValue<>() { 1161 @Override 1162 protected ConcurrentHashMap<Method, MethodHandle> computeValue(Class<?> type) { 1163 return new ConcurrentHashMap<>(4); 1164 } 1165 }; 1166 1167 private static ConcurrentHashMap<Method, MethodHandle> defaultMethodMap(Class<?> proxyClass) { 1168 assert isProxyClass(proxyClass); 1169 return DEFAULT_METHODS_MAP.get(proxyClass); 1170 } 1171 1172 static final Object[] EMPTY_ARGS = new Object[0]; 1173 1174 static MethodHandle defaultMethodHandle(Class<? extends Proxy> proxyClass, Method method) { 1175 // lookup the cached method handle 1176 ConcurrentHashMap<Method, MethodHandle> methods = defaultMethodMap(proxyClass); 1177 MethodHandle superMH = methods.get(method); 1178 if (superMH == null) { 1179 MethodType type = methodType(method.getReturnType(), method.getParameterTypes()); 1180 MethodHandles.Lookup lookup = MethodHandles.lookup(); 1181 Class<?> proxyInterface = findProxyInterfaceOrElseThrow(proxyClass, method); 1182 MethodHandle dmh; 1183 try { 1184 dmh = proxyClassLookup(lookup, proxyClass) 1185 .findSpecial(proxyInterface, method.getName(), type, proxyClass) 1186 .withVarargs(false); 1187 } catch (IllegalAccessException | NoSuchMethodException e) { 1188 // should not reach here 1189 throw new InternalError(e); 1190 } 1191 // this check can be turned into assertion as it is guaranteed to succeed by the virtue of 1192 // looking up a default (instance) method declared or inherited by proxyInterface 1193 // while proxyClass implements (is a subtype of) proxyInterface ... 1194 assert ((BooleanSupplier) () -> { 1195 try { 1196 // make sure that the method type matches 1197 dmh.asType(type.insertParameterTypes(0, proxyClass)); 1198 return true; 1199 } catch (WrongMethodTypeException e) { 1200 return false; 1201 } 1202 }).getAsBoolean() : "Wrong method type"; 1203 // change return type to Object 1204 MethodHandle mh = dmh.asType(dmh.type().changeReturnType(Object.class)); 1205 // wrap any exception thrown with InvocationTargetException 1206 mh = MethodHandles.catchException(mh, Throwable.class, InvocationException.wrapMH()); 1207 // spread array of arguments among parameters (skipping 1st parameter - target) 1208 mh = mh.asSpreader(1, Object[].class, type.parameterCount()); 1209 // change target type to Object 1210 mh = mh.asType(MethodType.methodType(Object.class, Object.class, Object[].class)); 1211 1212 // push MH into cache 1213 MethodHandle cached = methods.putIfAbsent(method, mh); 1214 if (cached != null) { 1215 superMH = cached; 1216 } else { 1217 superMH = mh; 1218 } 1219 } 1220 return superMH; 1221 } 1222 1223 /** 1224 * Finds the first proxy interface that declares the given method 1225 * directly or indirectly. 1226 * 1227 * @throws IllegalArgumentException if not found 1228 */ 1229 private static Class<?> findProxyInterfaceOrElseThrow(Class<?> proxyClass, Method method) { 1230 Class<?> declaringClass = method.getDeclaringClass(); 1231 if (!declaringClass.isInterface()) { 1232 throw new IllegalArgumentException("\"" + method + 1233 "\" is not a method declared in the proxy class"); 1234 } 1235 1236 List<Class<?>> proxyInterfaces = Arrays.asList(proxyClass.getInterfaces()); 1237 // the method's declaring class is a proxy interface 1238 if (proxyInterfaces.contains(declaringClass)) 1239 return declaringClass; 1240 1241 // find the first proxy interface that inherits the default method 1242 // i.e. the declaring class of the default method is a superinterface 1243 // of the proxy interface 1244 Deque<Class<?>> deque = new ArrayDeque<>(); 1245 Set<Class<?>> visited = new HashSet<>(); 1246 boolean indirectMethodRef = false; 1247 for (Class<?> proxyIntf : proxyInterfaces) { 1248 assert proxyIntf != declaringClass; 1249 visited.add(proxyIntf); 1250 deque.add(proxyIntf); 1251 1252 // for each proxy interface, traverse its subinterfaces with 1253 // breadth-first search to find a subinterface declaring the 1254 // default method 1255 Class<?> c; 1256 while ((c = deque.poll()) != null) { 1257 if (c == declaringClass) { 1258 try { 1259 // check if this method is the resolved method if referenced from 1260 // this proxy interface (i.e. this method is not implemented 1261 // by any other superinterface) 1262 Method m = proxyIntf.getMethod(method.getName(), method.getParameterTypes()); 1263 if (m.getDeclaringClass() == declaringClass) { 1264 return proxyIntf; 1265 } 1266 indirectMethodRef = true; 1267 } catch (NoSuchMethodException e) {} 1268 1269 // skip traversing its superinterfaces 1270 // another proxy interface may extend it and so 1271 // the method's declaring class is left unvisited. 1272 continue; 1273 } 1274 // visit all superinteraces of one proxy interface to find if 1275 // this proxy interface inherits the method directly or indirectly 1276 visited.add(c); 1277 for (Class<?> superIntf : c.getInterfaces()) { 1278 if (!visited.contains(superIntf) && !deque.contains(superIntf)) { 1279 if (superIntf == declaringClass) { 1280 // fast-path as the matching subinterface is found 1281 deque.addFirst(superIntf); 1282 } else { 1283 deque.add(superIntf); 1284 } 1285 } 1286 } 1287 } 1288 } 1289 1290 throw new IllegalArgumentException("\"" + method + (indirectMethodRef 1291 ? "\" is overridden directly or indirectly by the proxy interfaces" 1292 : "\" is not a method declared in the proxy class")); 1293 } 1294 1295 /** 1296 * This method invokes the proxy's proxyClassLookup method to get a 1297 * Lookup on the proxy class. 1298 * 1299 * @return a lookup for proxy class of this proxy instance 1300 */ 1301 @SuppressWarnings("removal") 1302 private static MethodHandles.Lookup proxyClassLookup(MethodHandles.Lookup caller, Class<?> proxyClass) { 1303 return AccessController.doPrivileged(new PrivilegedAction<>() { 1304 @Override 1305 public MethodHandles.Lookup run() { 1306 try { 1307 Method m = proxyClass.getDeclaredMethod("proxyClassLookup", MethodHandles.Lookup.class); 1308 m.setAccessible(true); 1309 return (MethodHandles.Lookup) m.invoke(null, caller); 1310 } catch (ReflectiveOperationException e) { 1311 throw new InternalError(e); 1312 } 1313 } 1314 }); 1315 } 1316 1317 /* 1318 * Invoke the default method of the given proxy with an explicit caller class. 1319 * 1320 * @throws IllegalAccessException if the proxy interface is inaccessible to the caller 1321 * if caller is non-null 1322 */ 1323 static Object invokeDefault(Object proxy, Method method, Object[] args, Class<?> caller) 1324 throws Throwable { 1325 // verify that the object is actually a proxy instance 1326 if (!Proxy.isProxyClass(proxy.getClass())) { 1327 throw new IllegalArgumentException("'proxy' is not a proxy instance"); 1328 } 1329 if (!method.isDefault()) { 1330 throw new IllegalArgumentException("\"" + method + "\" is not a default method"); 1331 } 1332 @SuppressWarnings("unchecked") 1333 Class<? extends Proxy> proxyClass = (Class<? extends Proxy>)proxy.getClass(); 1334 1335 // skip access check if caller is null 1336 if (caller != null) { 1337 Class<?> intf = method.getDeclaringClass(); 1338 // access check on the default method 1339 method.checkAccess(caller, intf, proxyClass, method.getModifiers()); 1340 } 1341 1342 MethodHandle mh = Proxy.defaultMethodHandle(proxyClass, method); 1343 // invoke the super method 1344 try { 1345 // the args array can be null if the number of formal parameters required by 1346 // the method is zero (consistent with Method::invoke) 1347 Object[] params = args != null ? args : Proxy.EMPTY_ARGS; 1348 return mh.invokeExact(proxy, params); 1349 } catch (ClassCastException | NullPointerException e) { 1350 throw new IllegalArgumentException(e.getMessage(), e); 1351 } catch (Proxy.InvocationException e) { 1352 // unwrap and throw the exception thrown by the default method 1353 throw e.getCause(); 1354 } 1355 } 1356 1357 /** 1358 * Internal exception type to wrap the exception thrown by the default method 1359 * so that it can distinguish CCE and NPE thrown due to the arguments 1360 * incompatible with the method signature. 1361 */ 1362 static class InvocationException extends ReflectiveOperationException { 1363 @java.io.Serial 1364 private static final long serialVersionUID = 0L; 1365 1366 InvocationException(Throwable cause) { 1367 super(cause); 1368 } 1369 1370 /** 1371 * Wraps given cause with InvocationException and throws it. 1372 */ 1373 static Object wrap(Throwable cause) throws InvocationException { 1374 throw new InvocationException(cause); 1375 } 1376 1377 @Stable 1378 static MethodHandle wrapMethodHandle; 1379 1380 static MethodHandle wrapMH() { 1381 MethodHandle mh = wrapMethodHandle; 1382 if (mh == null) { 1383 try { 1384 wrapMethodHandle = mh = MethodHandles.lookup().findStatic( 1385 InvocationException.class, 1386 "wrap", 1387 MethodType.methodType(Object.class, Throwable.class) 1388 ); 1389 } catch (NoSuchMethodException | IllegalAccessException e) { 1390 throw new InternalError(e); 1391 } 1392 } 1393 return mh; 1394 } 1395 } 1396 1397 }