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