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