1 /* 2 * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.reflect; 27 28 import java.lang.ref.WeakReference; 29 import java.security.AccessController; 30 import java.security.PrivilegedAction; 31 import java.util.Arrays; 32 import java.util.Collections; 33 import java.util.Deque; 34 import java.util.HashMap; 35 import java.util.HashSet; 36 import java.util.IdentityHashMap; 37 import java.util.LinkedList; 38 import java.util.List; 39 import java.util.Map; 40 import java.util.Objects; 41 import java.util.Set; 42 import java.util.WeakHashMap; 43 import java.util.concurrent.atomic.AtomicInteger; 44 import java.util.concurrent.atomic.AtomicLong; 45 import java.util.function.BiFunction; 46 import java.util.stream.Collectors; 47 import java.util.stream.Stream; 48 49 import jdk.internal.loader.BootLoader; 50 import jdk.internal.module.Modules; 51 import jdk.internal.misc.VM; 52 import sun.misc.Unsafe; 53 import sun.reflect.CallerSensitive; 54 import sun.reflect.Reflection; 55 import sun.reflect.misc.ReflectUtil; 56 import sun.security.util.SecurityConstants; 57 58 /** 59 * 60 * {@code Proxy} provides static methods for creating objects that act like instances 61 * of interfaces but allow for customized method invocation. 62 * To create a proxy instance for some interface {@code Foo}: 63 * <pre>{@code 64 * InvocationHandler handler = new MyInvocationHandler(...); 65 * Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), 66 * new Class<?>[] { Foo.class }, 67 * handler); 68 * }</pre> 69 * 70 * <p> 71 * A <em>proxy class</em> is a class created at runtime that implements a specified 72 * list of interfaces, known as <em>proxy interfaces</em>. A <em>proxy instance</em> 73 * is an instance of a proxy class. 74 * 75 * Each proxy instance has an associated <i>invocation handler</i> 76 * object, which implements the interface {@link InvocationHandler}. 77 * A method invocation on a proxy instance through one of its proxy 78 * interfaces will be dispatched to the {@link InvocationHandler#invoke 79 * invoke} method of the instance's invocation handler, passing the proxy 80 * instance, a {@code java.lang.reflect.Method} object identifying 81 * the method that was invoked, and an array of type {@code Object} 82 * containing the arguments. The invocation handler processes the 83 * encoded method invocation as appropriate and the result that it 84 * returns will be returned as the result of the method invocation on 85 * the proxy instance. 86 * 87 * <p>A proxy class has the following properties: 88 * 89 * <ul> 90 * <li>The unqualified name of a proxy class is unspecified. The space 91 * of class names that begin with the string {@code "$Proxy"} 92 * should be, however, reserved for proxy classes. 93 * 94 * <li>The package and module in which a proxy class is defined is specified 95 * <a href="#membership">below</a>. 96 * 97 * <li>A proxy class is <em>final and non-abstract</em>. 98 * 99 * <li>A proxy class extends {@code java.lang.reflect.Proxy}. 100 * 101 * <li>A proxy class implements exactly the interfaces specified at its 102 * creation, in the same order. Invoking {@link Class#getInterfaces getInterfaces} 103 * on its {@code Class} object will return an array containing the same 104 * list of interfaces (in the order specified at its creation), invoking 105 * {@link Class#getMethods getMethods} on its {@code Class} object will return 106 * an array of {@code Method} objects that include all of the 107 * methods in those interfaces, and invoking {@code getMethod} will 108 * find methods in the proxy interfaces as would be expected. 109 * 110 * <li>The {@link java.security.ProtectionDomain} of a proxy class 111 * is the same as that of system classes loaded by the bootstrap class 112 * loader, such as {@code java.lang.Object}, because the code for a 113 * proxy class is generated by trusted system code. This protection 114 * domain will typically be granted {@code java.security.AllPermission}. 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>An invocation of the {@code hashCode}, 147 * {@code equals}, or {@code toString} methods declared in 148 * {@code java.lang.Object} on a proxy instance will be encoded and 149 * dispatched to the invocation handler's {@code invoke} method in 150 * the same manner as interface method invocations are encoded and 151 * dispatched, as described above. The declaring class of the 152 * {@code Method} object passed to {@code invoke} will be 153 * {@code java.lang.Object}. Other public methods of a proxy 154 * instance inherited from {@code java.lang.Object} are not 155 * overridden by a proxy class, so invocations of those methods behave 156 * like they do for instances of {@code java.lang.Object}. 157 * </ul> 158 * 159 * <h3><a name="membership">Package and Module Membership of Proxy Class</a></h3> 160 * 161 * The package and module to which a proxy class belongs are chosen such that 162 * the accessibility of the proxy class is in line with the accessibility of 163 * the proxy interfaces. Specifically, the package and the module membership 164 * of a proxy class defined via the 165 * {@link Proxy#getProxyClass(ClassLoader, Class[])} or 166 * {@link Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler)} 167 * methods is specified as follows: 168 * 169 * <ol> 170 * <li>If all the proxy interfaces are in <em>exported</em> packages: 171 * <ol type="a"> 172 * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is 173 * <em>public</em> in a package exported by the 174 * {@linkplain ClassLoader#getUnnamedModule() unnamed module} of the specified 175 * loader. The name of the package is unspecified.</li> 176 * 177 * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then 178 * the proxy class is <em>non-public</em> in the package and module of the 179 * non-public interfaces. All the non-public interfaces must be in the same 180 * package and module; otherwise, proxying them is 181 * <a href="#restrictions">not possible</a>.</li> 182 * </ol> 183 * </li> 184 * <li>If at least one proxy interface is a <em>non-exported</em> package: 185 * <ol type="a"> 186 * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is 187 * <em>public</em> in a <em>non-exported</em> package of 188 * <a href="#dynamicmodule"><em>dynamic module</em>.</a> 189 * The names of the package and the module are unspecified.</li> 190 * 191 * <li>if at least one of all the proxy interfaces is <em>non-public</em>, then 192 * the proxy class is <em>non-public</em> in the package and module of the 193 * non-public interfaces. All the non-public interfaces must be in the same 194 * package and module; otherwise, proxying them is 195 * <a href="#restrictions">not possible</a>.</li> 196 * </ol> 197 * </li> 198 * </ol> 199 * 200 * <p> 201 * Note that if proxy interfaces with a mix of accessibilities -- 202 * exported public, exported non-public, non-exported public, non-exported non-public -- 203 * are proxied by the same instance, then the proxy class's accessibility is 204 * governed by the least accessible proxy interface. 205 * <p> 206 * Note that it is possible for arbitrary code to obtain access to a proxy class 207 * in an exported package with {@link AccessibleObject#setAccessible setAccessible}, 208 * whereas a proxy class in a non-exported package is never accessible to 209 * code outside the module of the proxy class. 210 * 211 * <p> 212 * Throughout this specification, a "non-exported package" refers to a package that 213 * is not exported to all modules. Specifically, it refers to a package that 214 * either is not exported at all by its containing module or is exported in a 215 * qualified fashion by its containing module. 216 * 217 * <h3><a name="dynamicmodule">Dynamic Modules</a></h3> 218 * <p> 219 * A dynamic module is a named module generated at runtime. A proxy class 220 * defined in a dynamic module is encapsulated and not accessible to any module. 221 * Calling {@link Constructor#newInstance(Object...)} on a proxy class in 222 * a dynamic module will throw {@code IllegalAccessException}; 223 * {@code Proxy.newProxyInstance} method should be used instead. 224 * 225 * <p> 226 * A dynamic module can read the modules of all of the superinterfaces of a proxy class 227 * and the modules of the types referenced by all public method signatures 228 * of a proxy class. If a superinterface or a referenced type, say {@code T}, 229 * is in a non-exported package, the {@linkplain java.lang.reflect.Module module} 230 * of {@code T} is updated to export the package of {@code T} to the dynamic module. 231 * 232 * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3> 233 * 234 * <p>When two or more proxy interfaces contain a method with 235 * the same name and parameter signature, the order of the proxy class's 236 * interfaces becomes significant. When such a <i>duplicate method</i> 237 * is invoked on a proxy instance, the {@code Method} object passed 238 * to the invocation handler will not necessarily be the one whose 239 * declaring class is assignable from the reference type of the interface 240 * that the proxy's method was invoked through. This limitation exists 241 * because the corresponding method implementation in the generated proxy 242 * class cannot determine which interface it was invoked through. 243 * Therefore, when a duplicate method is invoked on a proxy instance, 244 * the {@code Method} object for the method in the foremost interface 245 * that contains the method (either directly or inherited through a 246 * superinterface) in the proxy class's list of interfaces is passed to 247 * the invocation handler's {@code invoke} method, regardless of the 248 * reference type through which the method invocation occurred. 249 * 250 * <p>If a proxy interface contains a method with the same name and 251 * parameter signature as the {@code hashCode}, {@code equals}, 252 * or {@code toString} methods of {@code java.lang.Object}, 253 * when such a method is invoked on a proxy instance, the 254 * {@code Method} object passed to the invocation handler will have 255 * {@code java.lang.Object} as its declaring class. In other words, 256 * the public, non-final methods of {@code java.lang.Object} 257 * logically precede all of the proxy interfaces for the determination of 258 * which {@code Method} object to pass to the invocation handler. 259 * 260 * <p>Note also that when a duplicate method is dispatched to an 261 * invocation handler, the {@code invoke} method may only throw 262 * checked exception types that are assignable to one of the exception 263 * types in the {@code throws} clause of the method in <i>all</i> of 264 * the proxy interfaces that it can be invoked through. If the 265 * {@code invoke} method throws a checked exception that is not 266 * assignable to any of the exception types declared by the method in one 267 * of the proxy interfaces that it can be invoked through, then an 268 * unchecked {@code UndeclaredThrowableException} will be thrown by 269 * the invocation on the proxy instance. This restriction means that not 270 * all of the exception types returned by invoking 271 * {@code getExceptionTypes} on the {@code Method} object 272 * passed to the {@code invoke} method can necessarily be thrown 273 * successfully by the {@code invoke} method. 274 * 275 * @author Peter Jones 276 * @see InvocationHandler 277 * @since 1.3 278 */ 279 public class Proxy implements java.io.Serializable { 280 private static final long serialVersionUID = -2222568056686623797L; 281 282 /** parameter types of a proxy class constructor */ 283 private static final Class<?>[] constructorParams = 284 { InvocationHandler.class }; 285 286 /** 287 * the invocation handler for this proxy instance. 288 * @serial 289 */ 290 protected InvocationHandler h; 291 292 /** 293 * Prohibits instantiation. 294 */ 295 private Proxy() { 296 } 297 298 /** 299 * Constructs a new {@code Proxy} instance from a subclass 300 * (typically, a dynamic proxy class) with the specified value 301 * for its invocation handler. 302 * 303 * @param h the invocation handler for this proxy instance 304 * 305 * @throws NullPointerException if the given invocation handler, {@code h}, 306 * is {@code null}. 307 */ 308 protected Proxy(InvocationHandler h) { 309 Objects.requireNonNull(h); 310 this.h = h; 311 } 312 313 /** 314 * Returns the {@code java.lang.Class} object for a proxy class 315 * given a class loader and an array of interfaces. The proxy class 316 * will be defined by the specified class loader and will implement 317 * all of the supplied interfaces. If any of the given interfaces 318 * is non-public, the proxy class will be non-public. If a proxy class 319 * for the same permutation of interfaces has already been defined by the 320 * class loader, then the existing proxy class will be returned; otherwise, 321 * a proxy class for those interfaces will be generated dynamically 322 * and defined by the class loader. 323 * 324 * @param loader the class loader to define the proxy class 325 * @param interfaces the list of interfaces for the proxy class 326 * to implement 327 * @return a proxy class that is defined in the specified class loader 328 * and that implements the specified interfaces 329 * @throws IllegalArgumentException if any of the <a href="#restrictions"> 330 * restrictions</a> on the parameters are violated 331 * @throws SecurityException if a security manager, <em>s</em>, is present 332 * and any of the following conditions is met: 333 * <ul> 334 * <li> the given {@code loader} is {@code null} and 335 * the caller's class loader is not {@code null} and the 336 * invocation of {@link SecurityManager#checkPermission 337 * s.checkPermission} with 338 * {@code RuntimePermission("getClassLoader")} permission 339 * denies access.</li> 340 * <li> for each proxy interface, {@code intf}, 341 * the caller's class loader is not the same as or an 342 * ancestor of the class loader for {@code intf} and 343 * invocation of {@link SecurityManager#checkPackageAccess 344 * s.checkPackageAccess()} denies access to {@code intf}.</li> 345 * </ul> 346 * @throws NullPointerException if the {@code interfaces} array 347 * argument or any of its elements are {@code null} 348 * 349 * @deprecated Proxy classes generated in a named module are encapsulated and not 350 * accessible to code outside its module. 351 * {@link Constructor#newInstance(Object...) Constructor.newInstance} will throw 352 * {@code IllegalAccessException} when it is called on an inaccessible proxy class. 353 * Use {@link #newProxyInstance(ClassLoader, Class[], InvocationHandler)} 354 * to create a proxy instance instead. 355 * 356 * @see <a href="#membership">Package and Module Membership of Proxy Class</a> 357 */ 358 @Deprecated 359 @CallerSensitive 360 public static Class<?> getProxyClass(ClassLoader loader, 361 Class<?>... interfaces) 362 throws IllegalArgumentException 363 { 364 final List<Class<?>> intfs = Arrays.asList(interfaces.clone()); 365 final SecurityManager sm = System.getSecurityManager(); 366 final Class<?> caller = Reflection.getCallerClass(); 367 if (sm != null) { 368 checkProxyAccess(caller, loader, intfs); 369 } 370 371 return new ProxyBuilder(loader, intfs).build(); 372 } 373 374 /* 375 * Check permissions required to create a Proxy class. 376 * 377 * To define a proxy class, it performs the access checks as in 378 * Class.forName (VM will invoke ClassLoader.checkPackageAccess): 379 * 1. "getClassLoader" permission check if loader == null 380 * 2. checkPackageAccess on the interfaces it implements 381 * 382 * To get a constructor and new instance of a proxy class, it performs 383 * the package access check on the interfaces it implements 384 * as in Class.getConstructor. 385 * 386 * If an interface is non-public, the proxy class must be defined by 387 * the defining loader of the interface. If the caller's class loader 388 * is not the same as the defining loader of the interface, the VM 389 * will throw IllegalAccessError when the generated proxy class is 390 * being defined. 391 */ 392 private static void checkProxyAccess(Class<?> caller, 393 ClassLoader loader, 394 List<Class<?>> interfaces) 395 { 396 SecurityManager sm = System.getSecurityManager(); 397 if (sm != null) { 398 ClassLoader ccl = caller.getClassLoader(); 399 if (VM.isSystemDomainLoader(loader) && !VM.isSystemDomainLoader(ccl)) { 400 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 401 } 402 ReflectUtil.checkProxyPackageAccess(ccl, interfaces.toArray(EMPTY_CLASS_ARRAY)); 403 } 404 } 405 406 /* 407 * a key used for proxy class with 0 implemented interfaces 408 */ 409 private static final Object key0 = new Object(); 410 411 /* 412 * Key1 and Key2 are optimized for the common use of dynamic proxies 413 * that implement 1 or 2 interfaces. 414 */ 415 416 /* 417 * a key used for proxy class with 1 implemented interface 418 */ 419 private static final class Key1 extends WeakReference<Class<?>> { 420 private final int hash; 421 422 Key1(Class<?> intf) { 423 super(intf); 424 this.hash = intf.hashCode(); 425 } 426 427 @Override 428 public int hashCode() { 429 return hash; 430 } 431 432 @Override 433 public boolean equals(Object obj) { 434 Class<?> intf; 435 return this == obj || 436 obj != null && 437 obj.getClass() == Key1.class && 438 (intf = get()) != null && 439 intf == ((Key1) obj).get(); 440 } 441 } 442 443 /* 444 * a key used for proxy class with 2 implemented interfaces 445 */ 446 private static final class Key2 extends WeakReference<Class<?>> { 447 private final int hash; 448 private final WeakReference<Class<?>> ref2; 449 450 Key2(Class<?> intf1, Class<?> intf2) { 451 super(intf1); 452 hash = 31 * intf1.hashCode() + intf2.hashCode(); 453 ref2 = new WeakReference<>(intf2); 454 } 455 456 @Override 457 public int hashCode() { 458 return hash; 459 } 460 461 @Override 462 public boolean equals(Object obj) { 463 Class<?> intf1, intf2; 464 return this == obj || 465 obj != null && 466 obj.getClass() == Key2.class && 467 (intf1 = get()) != null && 468 intf1 == ((Key2) obj).get() && 469 (intf2 = ref2.get()) != null && 470 intf2 == ((Key2) obj).ref2.get(); 471 } 472 } 473 474 /* 475 * a key used for proxy class with any number of implemented interfaces 476 * (used here for 3 or more only) 477 */ 478 private static final class KeyX { 479 private final int hash; 480 private final WeakReference<Class<?>>[] refs; 481 482 @SuppressWarnings("unchecked") 483 KeyX(List<Class<?>> interfaces) { 484 hash = Arrays.hashCode(interfaces.toArray()); 485 refs = (WeakReference<Class<?>>[])new WeakReference<?>[interfaces.size()]; 486 int i = 0; 487 for (Class<?> intf : interfaces) { 488 refs[i++] = new WeakReference<>(intf); 489 } 490 } 491 492 @Override 493 public int hashCode() { 494 return hash; 495 } 496 497 @Override 498 public boolean equals(Object obj) { 499 return this == obj || 500 obj != null && 501 obj.getClass() == KeyX.class && 502 equals(refs, ((KeyX) obj).refs); 503 } 504 505 private static boolean equals(WeakReference<Class<?>>[] refs1, 506 WeakReference<Class<?>>[] refs2) { 507 if (refs1.length != refs2.length) { 508 return false; 509 } 510 for (int i = 0; i < refs1.length; i++) { 511 Class<?> intf = refs1[i].get(); 512 if (intf == null || intf != refs2[i].get()) { 513 return false; 514 } 515 } 516 return true; 517 } 518 } 519 520 /** 521 * A function that maps an array of interfaces to an optimal key where 522 * Class objects representing interfaces are weakly referenced. 523 */ 524 private static final class KeyFactory<T> 525 implements BiFunction<T, List<Class<?>>, Object> { 526 @Override 527 public Object apply(T t, List<Class<?>> interfaces) { 528 switch (interfaces.size()) { 529 case 1: return new Key1(interfaces.get(0)); // the most frequent 530 case 2: return new Key2(interfaces.get(0), interfaces.get(1)); 531 case 0: return key0; 532 default: return new KeyX(interfaces); 533 } 534 } 535 } 536 537 /** 538 * A factory function that generates, defines and returns the proxy class 539 * given the ClassLoader and array of interfaces. 540 */ 541 private static final class ProxyClassFactory { 542 private static final Unsafe UNSAFE = Unsafe.getUnsafe(); 543 544 // prefix for all proxy class names 545 private static final String proxyClassNamePrefix = "$Proxy"; 546 547 // next number to use for generation of unique proxy class names 548 private static final AtomicLong nextUniqueNumber = new AtomicLong(); 549 550 private static Class<?> defineProxyClass(Module m, List<Class<?>> interfaces) { 551 String proxyPkg = null; // package to define proxy class in 552 int accessFlags = Modifier.PUBLIC | Modifier.FINAL; 553 554 /* 555 * Record the package of a non-public proxy interface so that the 556 * proxy class will be defined in the same package. Verify that 557 * all non-public proxy interfaces are in the same package. 558 */ 559 for (Class<?> intf : interfaces) { 560 int flags = intf.getModifiers(); 561 if (!Modifier.isPublic(flags)) { 562 accessFlags = Modifier.FINAL; // non-public, final 563 String pkg = intf.getPackageName(); 564 if (proxyPkg == null) { 565 proxyPkg = pkg; 566 } else if (!pkg.equals(proxyPkg)) { 567 throw new IllegalArgumentException( 568 "non-public interfaces from different packages"); 569 } 570 } 571 } 572 573 if (proxyPkg == null) { 574 // all proxy interfaces are public 575 proxyPkg = m.isNamed() ? PROXY_PACKAGE_NAME + "." + m.getName() 576 : PROXY_PACKAGE_NAME; 577 } else if (proxyPkg.isEmpty() && m.isNamed()) { 578 throw new IllegalArgumentException( 579 "Unnamed package cannot be added to " + m); 580 } 581 582 // add the package to the runtime module if not exists 583 if (m.isNamed() && !Stream.of(m.getPackages()).anyMatch(proxyPkg::equals)) { 584 m.addPackage(proxyPkg); 585 } 586 587 /* 588 * Choose a name for the proxy class to generate. 589 */ 590 long num = nextUniqueNumber.getAndIncrement(); 591 String proxyName = proxyPkg.isEmpty() ? proxyClassNamePrefix + num 592 : proxyPkg + "." + proxyClassNamePrefix + num; 593 594 ClassLoader loader = getLoader(m); 595 trace(proxyName, m, loader, interfaces); 596 597 /* 598 * Generate the specified proxy class. 599 */ 600 byte[] proxyClassFile = ProxyGenerator.generateProxyClass( 601 proxyName, interfaces.toArray(EMPTY_CLASS_ARRAY), accessFlags); 602 try { 603 return UNSAFE.defineClass(proxyName, proxyClassFile, 0, proxyClassFile.length, 604 loader, null); 605 } catch (ClassFormatError e) { 606 /* 607 * A ClassFormatError here means that (barring bugs in the 608 * proxy class generation code) there was some other 609 * invalid aspect of the arguments supplied to the proxy 610 * class creation (such as virtual machine limitations 611 * exceeded). 612 */ 613 throw new IllegalArgumentException(e.toString()); 614 } 615 } 616 617 /** 618 * Test if the given class is a proxy class 619 */ 620 static boolean isProxyClass(Class<?> c) { 621 return proxyCache.containsValue(c); 622 } 623 624 /** 625 * Returns the proxy class. It will return the cached proxy class 626 * if exists; otherwise, it will create the proxy class and store in 627 * the cache. 628 */ 629 static Class<?> get(Module module, List<Class<?>> interfaces) { 630 return proxyCache.get(module, interfaces); 631 } 632 633 /** 634 * a cache of proxy classes in the named and unnamed module 635 */ 636 private static final WeakCache<Module, List<Class<?>>, Class<?>> proxyCache = 637 new WeakCache<>(new KeyFactory<Module>(), 638 new BiFunction<Module, List<Class<?>>, Class<?>>() { 639 @Override 640 public Class<?> apply(Module m, List<Class<?>> interfaces) { 641 Objects.requireNonNull(m); 642 return defineProxyClass(m, interfaces); 643 } 644 }); 645 646 647 private static boolean isExportedType(Class<?> c) { 648 String pn = c.getPackageName(); 649 return Modifier.isPublic(c.getModifiers()) && c.getModule().isExported(pn); 650 } 651 652 private static boolean isPackagePrivateType(Class<?> c) { 653 return !Modifier.isPublic(c.getModifiers()); 654 } 655 656 private static String toDetails(Class<?> c) { 657 String access = "unknown"; 658 if (isExportedType(c)) { 659 access = "exported"; 660 } else if (isPackagePrivateType(c)) { 661 access = "package-private"; 662 } else { 663 access = "module-private"; 664 } 665 ClassLoader ld = c.getClassLoader(); 666 return String.format(" %s/%s %s loader %s", 667 c.getModule().getName(), c.getName(), access, ld); 668 } 669 670 static void trace(String cn, Module module, ClassLoader loader, List<Class<?>> interfaces) { 671 if (isDebug()) { 672 System.out.format("PROXY: %s/%s defined by %s%n", module.getName(), cn, loader); 673 } 674 if (isDebug("debug")) { 675 interfaces.stream() 676 .forEach(c -> System.out.println(toDetails(c))); 677 } 678 } 679 680 private static final String DEBUG = 681 AccessController.doPrivileged(new PrivilegedAction<>() { 682 public String run() { 683 return System.getProperty("jdk.proxy.debug", ""); 684 } 685 }); 686 687 private static final boolean isDebug() { 688 return !DEBUG.isEmpty(); 689 } 690 private static final boolean isDebug(String flag) { 691 return DEBUG.equals(flag); 692 } 693 } 694 695 /** 696 * Builder for a proxy class. 697 * 698 * If the module is not specified in this ProxyBuilder constructor, 699 * it will map from the given loader and interfaces to the module 700 * in which the proxy class will be defined. 701 */ 702 private static final class ProxyBuilder { 703 final ClassLoader loader; 704 final List<Class<?>> interfaces; 705 final Module module; 706 ProxyBuilder(ClassLoader loader, List<Class<?>> interfaces) { 707 if (!VM.isModuleSystemInited()) { 708 throw new InternalError("Proxy is not supported until module system is fully initialzed"); 709 } 710 if (interfaces.size() > 65535) { 711 throw new IllegalArgumentException("interface limit exceeded"); 712 } 713 714 Set<Class<?>> refTypes = referencedTypes(loader, interfaces); 715 716 // IAE if violates any restrictions specified in newProxyInstance 717 validateProxyInterfaces(loader, interfaces, refTypes); 718 719 this.loader = loader; 720 this.interfaces = interfaces; 721 this.module = mapToModule(loader, interfaces, refTypes); 722 assert getLoader(module) == loader; 723 } 724 725 /** 726 * Generate a proxy class. If the target module does not have any 727 * to any interface types, IllegalAccessError will be thrown by the VM 728 * at defineClass time. 729 * 730 * Must call the checkProxyAccess method to perform permission checks 731 * before calling this. 732 */ 733 Class<?> build() { 734 return ProxyClassFactory.get(module, interfaces); 735 } 736 737 /** 738 * Validate the given proxy interfaces and the given referenced types 739 * are visible to the defining loader. 740 * 741 * @throws IllegalArgumentException if it violates the restrictions specified 742 * in {@link Proxy#newProxyInstance} 743 */ 744 static void validateProxyInterfaces(ClassLoader loader, 745 List<Class<?>> interfaces, 746 Set<Class<?>> refTypes) 747 { 748 Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.size()); 749 for (Class<?> intf : interfaces) { 750 /* 751 * Verify that the class loader resolves the name of this 752 * interface to the same Class object. 753 */ 754 ensureVisible(loader, intf); 755 756 /* 757 * Verify that the Class object actually represents an 758 * interface. 759 */ 760 if (!intf.isInterface()) { 761 throw new IllegalArgumentException(intf.getName() + " is not an interface"); 762 } 763 764 /* 765 * Verify that this interface is not a duplicate. 766 */ 767 if (interfaceSet.put(intf, Boolean.TRUE) != null) { 768 throw new IllegalArgumentException("repeated interface: " + intf.getName()); 769 } 770 } 771 772 for (Class<?> type : refTypes) { 773 ensureVisible(loader, type); 774 } 775 } 776 777 /* 778 * Returns all types referenced by all public method signatures of 779 * the proxy interfaces 780 */ 781 static Set<Class<?>> referencedTypes(ClassLoader loader, List<Class<?>> interfaces) { 782 Set<Class<?>> types = new HashSet<>(); 783 for (Class<?> intf : interfaces) { 784 for (Method m : intf.getMethods()) { 785 // return type, parameter types, and exception types 786 Stream.concat(Stream.concat(Stream.of(m.getReturnType()), 787 Arrays.stream(m.getParameterTypes())), 788 Arrays.stream(m.getExceptionTypes())) 789 .map(ProxyBuilder::getElementType) 790 .filter(t -> !t.isPrimitive()) 791 .forEach(types::add); 792 } 793 } 794 return types; 795 } 796 797 /** 798 * Returns the module that the generated proxy class belongs to. 799 * 800 * If all proxy interfaces are public and in exported packages, 801 * then the proxy class is in unnamed module. 802 * 803 * If any of proxy interface is package-private, then the proxy class 804 * is in the same module of the package-private interface. 805 * 806 * If all proxy interfaces are public and at least one in a non-exported 807 * package, then the proxy class is in a dynamic module in a non-exported 808 * package. Reads edge and qualified exports are added for 809 * dynamic module to access. 810 */ 811 static Module mapToModule(ClassLoader loader, List<Class<?>> interfaces, Set<Class<?>> refTypes) { 812 Map<Class<?>, Module> modulePrivateTypes = new HashMap<>(); 813 Map<Class<?>, Module> packagePrivateTypes = new HashMap<>(); 814 for (Class<?> intf : interfaces) { 815 Module m = intf.getModule(); 816 if (Modifier.isPublic(intf.getModifiers())) { 817 // module-private types 818 if (!m.isExported(intf.getPackageName())) { 819 modulePrivateTypes.put(intf, m); 820 } 821 } else { 822 packagePrivateTypes.put(intf, m); 823 } 824 } 825 826 // all proxy interfaces are public and exported, the proxy class is in unnamed module 827 // Such proxy class is accessible to any unnamed module and named module that 828 // can read unnamed module 829 if (packagePrivateTypes.isEmpty() && modulePrivateTypes.isEmpty()) { 830 return loader != null ? loader.getUnnamedModule() : BootLoader.getUnnamedModule(); 831 } 832 833 if (packagePrivateTypes.size() > 0) { 834 // all package-private types must be in the same runtime package 835 // i.e. same package name and same module (named or unnamed) 836 // 837 // Configuration will fail if M1 and in M2 defined by the same loader 838 // and both have the same package p (so no need to check class loader) 839 if (packagePrivateTypes.size() > 1 && 840 (packagePrivateTypes.keySet().stream() // more than one package 841 .map(Class::getPackageName).distinct().count() > 1 || 842 packagePrivateTypes.values().stream() // or more than one module 843 .distinct().count() > 1)) { 844 throw new IllegalArgumentException( 845 "non-public interfaces from different packages"); 846 } 847 848 // all package-private types are in the same module (named or unnamed) 849 Module target = null; 850 for (Module m : packagePrivateTypes.values()) { 851 if (getLoader(m) != loader) { 852 // the specified loader is not the same class loader of the non-public interface 853 throw new IllegalArgumentException( 854 "non-public interface is not defined by the given loader"); 855 } 856 target = m; 857 } 858 859 // validate if the target module can access all other interfaces 860 for (Class<?> intf : interfaces) { 861 Module m = intf.getModule(); 862 if (m == target) continue; 863 864 if (!target.canRead(m) || !m.isExported(intf.getPackageName(), target)) { 865 throw new IllegalArgumentException(target + " can't access " + intf.getName()); 866 } 867 } 868 869 // return the module of the package-private interface 870 return target; 871 } 872 873 // all proxy interfaces are public and at least one in a non-exported package 874 // map to dynamic proxy module and add reads edge and qualified exports, if necessary 875 Module target = getDynamicModule(loader); 876 877 // set up proxy class access to proxy interfaces and superinterfaces 878 Deque<Class<?>> deque = new LinkedList<>(interfaces); 879 Set<Class<?>> visited = new HashSet<>(); 880 while (!deque.isEmpty()) { 881 Class<?> c = deque.poll(); 882 if (visited.contains(c)) { 883 continue; 884 } 885 visited.add(c); 886 ensureAccess(target, c); 887 888 // add all superinterfaces 889 for (Class<?> intf : c.getInterfaces()) { 890 deque.add(intf); 891 } 892 } 893 894 // set up proxy class access to types referenced in the method signature 895 refTypes.stream() 896 .filter(t -> !visited.contains(t)) 897 .forEach(t -> ensureAccess(target, t)); 898 return target; 899 } 900 901 /* 902 * Ensure the given module can access the given class. 903 */ 904 static void ensureAccess(Module target, Class<?> c) { 905 Module m = c.getModule(); 906 // add read edge and qualified export for the target module to access 907 if (!target.canRead(m)) { 908 Modules.addReads(target, m); 909 } 910 String pn = c.getPackageName(); 911 if (!m.isExported(pn, target)) { 912 Modules.addExports(m, pn, target); 913 } 914 } 915 916 /* 917 * Ensure the given class is visible to the class loader. 918 */ 919 static void ensureVisible(ClassLoader ld, Class<?> c) { 920 Class<?> type = null; 921 try { 922 type = Class.forName(c.getName(), false, ld); 923 } catch (ClassNotFoundException e) { 924 } 925 if (type != c) { 926 throw new IllegalArgumentException(c.getName() + 927 " referenced from a method is not visible from class loader"); 928 } 929 } 930 931 static Class<?> getElementType(Class<?> type) { 932 Class<?> e = type; 933 while (e.isArray()) { 934 e = e.getComponentType(); 935 } 936 return e; 937 } 938 939 private static final WeakHashMap<ClassLoader, Module> dynProxyModules = new WeakHashMap<>(); 940 private static final AtomicInteger counter = new AtomicInteger(); 941 942 /* 943 * Define a dynamic module for the generated proxy classes in a non-exported package 944 * named com.sun.proxy.$MODULE. 945 * 946 * Each class loader will have one dynamic module. 947 */ 948 static synchronized Module getDynamicModule(ClassLoader loader) { 949 Module m = dynProxyModules.get(loader); 950 if (m == null) { 951 String mn = "jdk.proxy" + counter.incrementAndGet(); 952 String pn = PROXY_PACKAGE_NAME + "." + mn; 953 m = Modules.defineModule(loader, mn, Collections.singleton(pn)); 954 Modules.addReads(m, Proxy.class.getModule()); 955 // java.base to create proxy instance 956 Modules.addExports(m, pn, Object.class.getModule()); 957 dynProxyModules.put(loader, m); 958 } 959 return m; 960 } 961 } 962 963 /** 964 * Returns a proxy instance for the specified interfaces 965 * that dispatches method invocations to the specified invocation 966 * handler. 967 * <p> 968 * <a name="restrictions">{@code IllegalArgumentException} will be thrown 969 * if any of the following restrictions is violated:</a> 970 * <ul> 971 * <li>All of {@code Class} objects in the given {@code interfaces} array 972 * must represent interfaces, not classes or primitive types. 973 * 974 * <li>No two elements in the {@code interfaces} array may 975 * refer to identical {@code Class} objects. 976 * 977 * <li>All of the interface types must be visible by name through the 978 * specified class loader. In other words, for class loader 979 * {@code cl} and every interface {@code i}, the following 980 * expression must be true:<p> 981 * {@code Class.forName(i.getName(), false, cl) == i} 982 * 983 * <li>All of the types referenced by all 984 * public method signatures of the specified interfaces 985 * and those inherited by their superinterfaces 986 * must be visible by name through the specified class loader. 987 * 988 * <li>All non-public interfaces must be in the same package 989 * and module, defined by the specified class loader and 990 * the module of the non-public interfaces can access all of 991 * the interface types; otherwise, it would not be possible for 992 * the proxy class to implement all of the interfaces, 993 * regardless of what package it is defined in. 994 * 995 * <li>For any set of member methods of the specified interfaces 996 * that have the same signature: 997 * <ul> 998 * <li>If the return type of any of the methods is a primitive 999 * type or void, then all of the methods must have that same 1000 * return type. 1001 * <li>Otherwise, one of the methods must have a return type that 1002 * is assignable to all of the return types of the rest of the 1003 * methods. 1004 * </ul> 1005 * 1006 * <li>The resulting proxy class must not exceed any limits imposed 1007 * on classes by the virtual machine. For example, the VM may limit 1008 * the number of interfaces that a class may implement to 65535; in 1009 * that case, the size of the {@code interfaces} array must not 1010 * exceed 65535. 1011 * </ul> 1012 * 1013 * <p>Note that the order of the specified proxy interfaces is 1014 * significant: two requests for a proxy class with the same combination 1015 * of interfaces but in a different order will result in two distinct 1016 * proxy classes. 1017 * 1018 * @param loader the class loader to define the proxy class 1019 * @param interfaces the list of interfaces for the proxy class 1020 * to implement 1021 * @param h the invocation handler to dispatch method invocations to 1022 * @return a proxy instance with the specified invocation handler of a 1023 * proxy class that is defined by the specified class loader 1024 * and that implements the specified interfaces 1025 * @throws IllegalArgumentException if any of the <a href="#restrictions"> 1026 * restrictions</a> on the parameters are violated 1027 * @throws SecurityException if a security manager, <em>s</em>, is present 1028 * and any of the following conditions is met: 1029 * <ul> 1030 * <li> the given {@code loader} is {@code null} and 1031 * the caller's class loader is not {@code null} and the 1032 * invocation of {@link SecurityManager#checkPermission 1033 * s.checkPermission} with 1034 * {@code RuntimePermission("getClassLoader")} permission 1035 * denies access;</li> 1036 * <li> for each proxy interface, {@code intf}, 1037 * the caller's class loader is not the same as or an 1038 * ancestor of the class loader for {@code intf} and 1039 * invocation of {@link SecurityManager#checkPackageAccess 1040 * s.checkPackageAccess()} denies access to {@code intf};</li> 1041 * <li> any of the given proxy interfaces is non-public and the 1042 * caller class is not in the same {@linkplain Package runtime package} 1043 * as the non-public interface and the invocation of 1044 * {@link SecurityManager#checkPermission s.checkPermission} with 1045 * {@code ReflectPermission("newProxyInPackage.{package name}")} 1046 * permission denies access.</li> 1047 * </ul> 1048 * @throws NullPointerException if the {@code interfaces} array 1049 * argument or any of its elements are {@code null}, or 1050 * if the invocation handler, {@code h}, is 1051 * {@code null} 1052 * 1053 * @see <a href="#membership">Package and Module Membership of Proxy Class</a> 1054 */ 1055 @CallerSensitive 1056 public static Object newProxyInstance(ClassLoader loader, 1057 Class<?>[] interfaces, 1058 InvocationHandler h) { 1059 Objects.requireNonNull(h); 1060 1061 final List<Class<?>> intfs = Arrays.asList(interfaces.clone()); 1062 final SecurityManager sm = System.getSecurityManager(); 1063 final Class<?> caller = Reflection.getCallerClass(); 1064 if (sm != null) { 1065 checkProxyAccess(caller, loader, intfs); 1066 } 1067 1068 /* 1069 * Look up or generate the designated proxy class. 1070 */ 1071 Class<?> cl = new ProxyBuilder(loader, intfs).build(); 1072 1073 return newProxyInstance(cl, caller, h); 1074 } 1075 1076 private static Object newProxyInstance(Class<?> proxyClass, Class<?> caller, InvocationHandler h) { 1077 /* 1078 * Invoke its constructor with the designated invocation handler. 1079 */ 1080 try { 1081 final SecurityManager sm = System.getSecurityManager(); 1082 if (sm != null) { 1083 checkNewProxyPermission(caller, proxyClass); 1084 } 1085 1086 final Constructor<?> cons = proxyClass.getConstructor(constructorParams); 1087 AccessController.doPrivileged(new PrivilegedAction<Void>() { 1088 public Void run() { 1089 cons.setAccessible(true); 1090 return null; 1091 } 1092 }); 1093 return cons.newInstance(new Object[]{h}); 1094 } catch (IllegalAccessException | InstantiationException | NoSuchMethodException e) { 1095 throw new InternalError(e.toString(), e); 1096 } catch (InvocationTargetException e) { 1097 Throwable t = e.getCause(); 1098 if (t instanceof RuntimeException) { 1099 throw (RuntimeException) t; 1100 } else { 1101 throw new InternalError(t.toString(), t); 1102 } 1103 } 1104 } 1105 1106 // ## this permission check may need to extend for module-private types 1107 private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) { 1108 SecurityManager sm = System.getSecurityManager(); 1109 if (sm != null) { 1110 if (ReflectUtil.isNonPublicProxyClass(proxyClass)) { 1111 ClassLoader ccl = caller.getClassLoader(); 1112 ClassLoader pcl = proxyClass.getClassLoader(); 1113 1114 // do permission check if the caller is in a different runtime package 1115 // of the proxy class 1116 int n = proxyClass.getName().lastIndexOf('.'); 1117 String pkg = (n == -1) ? "" : proxyClass.getName().substring(0, n); 1118 1119 n = caller.getName().lastIndexOf('.'); 1120 String callerPkg = (n == -1) ? "" : caller.getName().substring(0, n); 1121 1122 if (pcl != ccl || !pkg.equals(callerPkg)) { 1123 sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg)); 1124 } 1125 } 1126 } 1127 } 1128 1129 /** 1130 * Returns the class loader for the given module. 1131 */ 1132 private static ClassLoader getLoader(Module m) { 1133 PrivilegedAction<ClassLoader> pa = m::getClassLoader; 1134 return AccessController.doPrivileged(pa); 1135 } 1136 1137 /** 1138 * Returns true if the given class is a proxy class. 1139 * 1140 * @implNote The reliability of this method is important for the ability 1141 * to use it to make security decisions, so its implementation should 1142 * not just test if the class in question extends {@code Proxy}. 1143 * 1144 * @param cl the class to test 1145 * @return {@code true} if the class is a proxy class and 1146 * {@code false} otherwise 1147 * @throws NullPointerException if {@code cl} is {@code null} 1148 */ 1149 public static boolean isProxyClass(Class<?> cl) { 1150 return Proxy.class.isAssignableFrom(cl) && ProxyClassFactory.isProxyClass(cl); 1151 } 1152 1153 /** 1154 * Returns the invocation handler for the specified proxy instance. 1155 * 1156 * @param proxy the proxy instance to return the invocation handler for 1157 * @return the invocation handler for the proxy instance 1158 * @throws IllegalArgumentException if the argument is not a 1159 * proxy instance 1160 * @throws SecurityException if a security manager, <em>s</em>, is present 1161 * and the caller's class loader is not the same as or an 1162 * ancestor of the class loader for the invocation handler 1163 * and invocation of {@link SecurityManager#checkPackageAccess 1164 * s.checkPackageAccess()} denies access to the invocation 1165 * handler's class. 1166 */ 1167 @CallerSensitive 1168 public static InvocationHandler getInvocationHandler(Object proxy) 1169 throws IllegalArgumentException 1170 { 1171 /* 1172 * Verify that the object is actually a proxy instance. 1173 */ 1174 if (!isProxyClass(proxy.getClass())) { 1175 throw new IllegalArgumentException("not a proxy instance"); 1176 } 1177 1178 final Proxy p = (Proxy) proxy; 1179 final InvocationHandler ih = p.h; 1180 if (System.getSecurityManager() != null) { 1181 Class<?> ihClass = ih.getClass(); 1182 Class<?> caller = Reflection.getCallerClass(); 1183 if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), 1184 ihClass.getClassLoader())) 1185 { 1186 ReflectUtil.checkPackageAccess(ihClass); 1187 } 1188 } 1189 1190 return ih; 1191 } 1192 1193 private static Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0]; 1194 private static final String PROXY_PACKAGE_NAME = ReflectUtil.PROXY_PACKAGE; 1195 }