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