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