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