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.io.IOException;
 29 import java.lang.classfile.*;
 30 import java.lang.classfile.attribute.ExceptionsAttribute;
 31 import java.lang.classfile.constantpool.*;
 32 import java.lang.constant.ClassDesc;
 33 import java.lang.constant.MethodTypeDesc;
 34 import java.nio.file.Files;
 35 import java.nio.file.Path;
 36 import java.util.ArrayList;
 37 import java.util.LinkedHashMap;
 38 import java.util.List;
 39 import java.util.ListIterator;
 40 import java.util.Map;
 41 import java.util.Objects;
 42 
 43 import jdk.internal.constant.ClassOrInterfaceDescImpl;
 44 import jdk.internal.constant.ConstantUtils;
 45 import jdk.internal.constant.MethodTypeDescImpl;
 46 
 47 import static java.lang.classfile.ClassFile.*;
 48 import java.lang.classfile.attribute.StackMapFrameInfo;
 49 import java.lang.classfile.attribute.StackMapTableAttribute;
 50 
 51 import static java.lang.constant.ConstantDescs.*;
 52 import static jdk.internal.constant.ConstantUtils.*;
 53 
 54 /**
 55  * ProxyGenerator contains the code to generate a dynamic proxy class
 56  * for the java.lang.reflect.Proxy API.
 57  * <p>
 58  * The external interface to ProxyGenerator is the static
 59  * "generateProxyClass" method.
 60  */
 61 final class ProxyGenerator {
 62 
 63     private static final ClassFile CF_CONTEXT =
 64             ClassFile.of(ClassFile.StackMapsOption.DROP_STACK_MAPS);
 65 
 66     private static final ClassDesc
 67             CD_ClassLoader = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/ClassLoader;"),
 68             CD_Class_array = CD_Class.arrayType(),
 69             CD_ClassNotFoundException = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/ClassNotFoundException;"),
 70             CD_NoClassDefFoundError = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/NoClassDefFoundError;"),
 71             CD_IllegalAccessException = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/IllegalAccessException;"),
 72             CD_InvocationHandler = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/reflect/InvocationHandler;"),
 73             CD_Method = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/reflect/Method;"),
 74             CD_NoSuchMethodError = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/NoSuchMethodError;"),
 75             CD_NoSuchMethodException = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/NoSuchMethodException;"),
 76             CD_Object_array = ConstantUtils.CD_Object_array,
 77             CD_Proxy = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/reflect/Proxy;"),
 78             CD_UndeclaredThrowableException = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/reflect/UndeclaredThrowableException;");
 79 
 80     private static final MethodTypeDesc
 81             MTD_boolean = MethodTypeDescImpl.ofValidated(CD_boolean),
 82             MTD_void_InvocationHandler = MethodTypeDescImpl.ofValidated(CD_void, CD_InvocationHandler),
 83             MTD_void_String = MethodTypeDescImpl.ofValidated(CD_void, CD_String),
 84             MTD_void_Throwable = MethodTypeDescImpl.ofValidated(CD_void, CD_Throwable),
 85             MTD_Class = MethodTypeDescImpl.ofValidated(CD_Class),
 86             MTD_Class_String_boolean_ClassLoader = MethodTypeDescImpl.ofValidated(CD_Class, CD_String, CD_boolean, CD_ClassLoader),
 87             MTD_ClassLoader = MethodTypeDescImpl.ofValidated(CD_ClassLoader),
 88             MTD_Method_String_Class_array = MethodTypeDescImpl.ofValidated(CD_Method, CD_String, CD_Class_array),
 89             MTD_MethodHandles$Lookup = MethodTypeDescImpl.ofValidated(CD_MethodHandles_Lookup),
 90             MTD_MethodHandles$Lookup_MethodHandles$Lookup = MethodTypeDescImpl.ofValidated(CD_MethodHandles_Lookup, CD_MethodHandles_Lookup),
 91             MTD_Object_Object_Method_ObjectArray = MethodTypeDescImpl.ofValidated(CD_Object, CD_Object, CD_Method, CD_Object_array),
 92             MTD_String = MethodTypeDescImpl.ofValidated(CD_String);
 93 
 94     private static final String NAME_LOOKUP_ACCESSOR = "proxyClassLookup";
 95 
 96     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
 97 
 98     /**
 99      * name of field for storing a proxy instance's invocation handler
100      */
101     private static final String NAME_HANDLER_FIELD = "h";
102 
103     /**
104      * debugging flag for saving generated class files
105      */
106     private static final boolean SAVE_GENERATED_FILES =
107             Boolean.getBoolean("jdk.proxy.ProxyGenerator.saveGeneratedFiles");
108 
109 
110     /* Preloaded ProxyMethod objects for methods in java.lang.Object */
111     private static final Method OBJECT_HASH_CODE_METHOD;
112     private static final Method OBJECT_EQUALS_METHOD;
113     private static final Method OBJECT_TO_STRING_METHOD;
114 
115     private static final String OBJECT_HASH_CODE_SIG;
116     private static final String OBJECT_EQUALS_SIG;
117     private static final String OBJECT_TO_STRING_SIG;
118 
119     static {
120         try {
121             OBJECT_HASH_CODE_METHOD = Object.class.getMethod("hashCode");
122             OBJECT_HASH_CODE_SIG = OBJECT_HASH_CODE_METHOD.toShortSignature();
123             OBJECT_EQUALS_METHOD = Object.class.getMethod("equals", Object.class);
124             OBJECT_EQUALS_SIG = OBJECT_EQUALS_METHOD.toShortSignature();
125             OBJECT_TO_STRING_METHOD = Object.class.getMethod("toString");
126             OBJECT_TO_STRING_SIG = OBJECT_TO_STRING_METHOD.toShortSignature();
127         } catch (NoSuchMethodException e) {
128             throw new NoSuchMethodError(e.getMessage());
129         }
130     }
131 
132     private final ConstantPoolBuilder cp;
133     private final List<StackMapFrameInfo.VerificationTypeInfo> classLoaderLocal, throwableStack;
134     private final NameAndTypeEntry exInit;
135     private final ClassEntry objectCE, proxyCE, uteCE, classCE;
136     private final FieldRefEntry handlerField;
137     private final InterfaceMethodRefEntry invocationHandlerInvoke;
138     private final MethodRefEntry uteInit, classGetMethod, classForName, throwableGetMessage;
139 
140 
141     /**
142      * ClassEntry for this proxy class
143      */
144     private final ClassEntry thisClassCE;
145 
146     /**
147      * Proxy interfaces
148      */
149     private final List<Class<?>> interfaces;
150 
151     /**
152      * Proxy class access flags
153      */
154     private final int accessFlags;
155 
156     /**
157      * Maps method signature string to list of ProxyMethod objects for
158      * proxy methods with that signature.
159      * Kept in insertion order to make it easier to compare old and new.
160      */
161     private final Map<String, List<ProxyMethod>> proxyMethods = new LinkedHashMap<>();
162 
163     /**
164      * Ordinal of next ProxyMethod object added to proxyMethods.
165      * Indexes are reserved for hashcode(0), equals(1), toString(2).
166      */
167     private int proxyMethodCount = 3;
168 
169     /**
170      * Construct a ProxyGenerator to generate a proxy class with the
171      * specified name and for the given interfaces.
172      * <p>
173      * A ProxyGenerator object contains the state for the ongoing
174      * generation of a particular proxy class.
175      */
176     private ProxyGenerator(String className, List<Class<?>> interfaces,
177                            int accessFlags) {
178         this.cp = ConstantPoolBuilder.of();
179         this.thisClassCE = cp.classEntry(ConstantUtils.binaryNameToDesc(className));
180         this.interfaces = interfaces;
181         this.accessFlags = accessFlags;
182         var throwable = cp.classEntry(CD_Throwable);
183         this.classLoaderLocal = List.of(StackMapFrameInfo.ObjectVerificationTypeInfo.of(cp.classEntry(CD_ClassLoader)));
184         this.throwableStack = List.of(StackMapFrameInfo.ObjectVerificationTypeInfo.of(throwable));
185         this.exInit = cp.nameAndTypeEntry(INIT_NAME, MTD_void_String);
186         this.objectCE = cp.classEntry(CD_Object);
187         this.proxyCE = cp.classEntry(CD_Proxy);
188         this.classCE = cp.classEntry(CD_Class);
189         this.handlerField = cp.fieldRefEntry(proxyCE, cp.nameAndTypeEntry(NAME_HANDLER_FIELD, CD_InvocationHandler));
190         this.invocationHandlerInvoke = cp.interfaceMethodRefEntry(CD_InvocationHandler, "invoke", MTD_Object_Object_Method_ObjectArray);
191         this.uteCE = cp.classEntry(CD_UndeclaredThrowableException);
192         this.uteInit = cp.methodRefEntry(uteCE, cp.nameAndTypeEntry(INIT_NAME, MTD_void_Throwable));
193         this.classGetMethod = cp.methodRefEntry(classCE, cp.nameAndTypeEntry("getMethod", MTD_Method_String_Class_array));
194         this.classForName = cp.methodRefEntry(classCE, cp.nameAndTypeEntry("forName", MTD_Class_String_boolean_ClassLoader));
195         this.throwableGetMessage = cp.methodRefEntry(throwable, cp.nameAndTypeEntry("getMessage", MTD_String));
196     }
197 
198     /**
199      * Generate a proxy class given a name and a list of proxy interfaces.
200      *
201      * @param name        the class name of the proxy class
202      * @param interfaces  proxy interfaces
203      * @param accessFlags access flags of the proxy class
204      */
205     static byte[] generateProxyClass(ClassLoader loader,
206                                      final String name,
207                                      List<Class<?>> interfaces,
208                                      int accessFlags) {
209         Objects.requireNonNull(interfaces);
210         ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
211         final byte[] classFile = gen.generateClassFile();
212 
213         if (SAVE_GENERATED_FILES) {
214             try {
215                 int i = name.lastIndexOf('.');
216                 Path path;
217                 if (i > 0) {
218                     Path dir = Path.of(name.substring(0, i).replace('.', '/'));
219                     Files.createDirectories(dir);
220                     path = dir.resolve(name.substring(i + 1) + ".class");
221                 } else {
222                     path = Path.of(name + ".class");
223                 }
224                 Files.write(path, classFile);
225             } catch (IOException e) {
226                 throw new InternalError("I/O exception saving generated file: " + e);
227             }
228         }
229 
230         return classFile;
231     }
232 
233     /**
234      * {@return the entries of the given type}
235      * @param types the {@code Class} objects, not primitive types nor array types
236      */
237     private static List<ClassEntry> toClassEntries(ConstantPoolBuilder cp, List<Class<?>> types) {
238         var ces = new ArrayList<ClassEntry>(types.size());
239         for (var t : types)
240             ces.add(cp.classEntry(ConstantUtils.binaryNameToDesc(t.getName())));
241         return ces;
242     }
243 
244     /**
245      * For a given set of proxy methods with the same signature, check
246      * that their return types are compatible according to the Proxy
247      * specification.
248      *
249      * Specifically, if there is more than one such method, then all
250      * of the return types must be reference types, and there must be
251      * one return type that is assignable to each of the rest of them.
252      */
253     private static void checkReturnTypes(List<ProxyMethod> methods) {
254         /*
255          * If there is only one method with a given signature, there
256          * cannot be a conflict.  This is the only case in which a
257          * primitive (or void) return type is allowed.
258          */
259         if (methods.size() < 2) {
260             return;
261         }
262 
263         /*
264          * List of return types that are not yet known to be
265          * assignable from ("covered" by) any of the others.
266          */
267         List<Class<?>> uncoveredReturnTypes = new ArrayList<>(1);
268 
269         nextNewReturnType:
270         for (ProxyMethod pm : methods) {
271             Class<?> newReturnType = pm.returnType;
272             if (newReturnType.isPrimitive()) {
273                 throw new IllegalArgumentException(
274                         "methods with same signature " +
275                                 pm.shortSignature +
276                                 " but incompatible return types: " +
277                                 newReturnType.getName() + " and others");
278             }
279             boolean added = false;
280 
281             /*
282              * Compare the new return type to the existing uncovered
283              * return types.
284              */
285             ListIterator<Class<?>> liter = uncoveredReturnTypes.listIterator();
286             while (liter.hasNext()) {
287                 Class<?> uncoveredReturnType = liter.next();
288 
289                 /*
290                  * If an existing uncovered return type is assignable
291                  * to this new one, then we can forget the new one.
292                  */
293                 if (newReturnType.isAssignableFrom(uncoveredReturnType)) {
294                     assert !added;
295                     continue nextNewReturnType;
296                 }
297 
298                 /*
299                  * If the new return type is assignable to an existing
300                  * uncovered one, then should replace the existing one
301                  * with the new one (or just forget the existing one,
302                  * if the new one has already be put in the list).
303                  */
304                 if (uncoveredReturnType.isAssignableFrom(newReturnType)) {
305                     // (we can assume that each return type is unique)
306                     if (!added) {
307                         liter.set(newReturnType);
308                         added = true;
309                     } else {
310                         liter.remove();
311                     }
312                 }
313             }
314 
315             /*
316              * If we got through the list of existing uncovered return
317              * types without an assignability relationship, then add
318              * the new return type to the list of uncovered ones.
319              */
320             if (!added) {
321                 uncoveredReturnTypes.add(newReturnType);
322             }
323         }
324 
325         /*
326          * We shouldn't end up with more than one return type that is
327          * not assignable from any of the others.
328          */
329         if (uncoveredReturnTypes.size() > 1) {
330             ProxyMethod pm = methods.getFirst();
331             throw new IllegalArgumentException(
332                     "methods with same signature " +
333                             pm.shortSignature +
334                             " but incompatible return types: " + uncoveredReturnTypes);
335         }
336     }
337 
338     /**
339      * Given the exceptions declared in the throws clause of a proxy method,
340      * compute the exceptions that need to be caught from the invocation
341      * handler's invoke method and rethrown intact in the method's
342      * implementation before catching other Throwables and wrapping them
343      * in UndeclaredThrowableExceptions.
344      *
345      * The exceptions to be caught are returned in a List object.  Each
346      * exception in the returned list is guaranteed to not be a subclass of
347      * any of the other exceptions in the list, so the catch blocks for
348      * these exceptions may be generated in any order relative to each other.
349      *
350      * Error and RuntimeException are each always contained by the returned
351      * list (if none of their superclasses are contained), since those
352      * unchecked exceptions should always be rethrown intact, and thus their
353      * subclasses will never appear in the returned list.
354      *
355      * The returned List will be empty if java.lang.Throwable is in the
356      * given list of declared exceptions, indicating that no exceptions
357      * need to be caught.
358      */
359     private static List<Class<?>> computeUniqueCatchList(Class<?>[] exceptions) {
360         List<Class<?>> uniqueList = new ArrayList<>();
361         // unique exceptions to catch
362 
363         uniqueList.add(Error.class);            // always catch/rethrow these
364         uniqueList.add(RuntimeException.class);
365 
366         nextException:
367         for (Class<?> ex : exceptions) {
368             if (ex.isAssignableFrom(Throwable.class)) {
369                 /*
370                  * If Throwable is declared to be thrown by the proxy method,
371                  * then no catch blocks are necessary, because the invoke
372                  * can, at most, throw Throwable anyway.
373                  */
374                 uniqueList.clear();
375                 break;
376             } else if (!Throwable.class.isAssignableFrom(ex)) {
377                 /*
378                  * Ignore types that cannot be thrown by the invoke method.
379                  */
380                 continue;
381             }
382             /*
383              * Compare this exception against the current list of
384              * exceptions that need to be caught:
385              */
386             for (int j = 0; j < uniqueList.size(); ) {
387                 Class<?> ex2 = uniqueList.get(j);
388                 if (ex2.isAssignableFrom(ex)) {
389                     /*
390                      * if a superclass of this exception is already on
391                      * the list to catch, then ignore this one and continue;
392                      */
393                     continue nextException;
394                 } else if (ex.isAssignableFrom(ex2)) {
395                     /*
396                      * if a subclass of this exception is on the list
397                      * to catch, then remove it;
398                      */
399                     uniqueList.remove(j);
400                 } else {
401                     j++;        // else continue comparing.
402                 }
403             }
404             // This exception is unique (so far): add it to the list to catch.
405             uniqueList.add(ex);
406         }
407         return uniqueList;
408     }
409 
410     /**
411      * Add to the given list all of the types in the "from" array that
412      * are not already contained in the list and are assignable to at
413      * least one of the types in the "with" array.
414      * <p>
415      * This method is useful for computing the greatest common set of
416      * declared exceptions from duplicate methods inherited from
417      * different interfaces.
418      */
419     private static void collectCompatibleTypes(Class<?>[] from,
420                                                Class<?>[] with,
421                                                List<Class<?>> list) {
422         for (Class<?> fc : from) {
423             if (!list.contains(fc)) {
424                 for (Class<?> wc : with) {
425                     if (wc.isAssignableFrom(fc)) {
426                         list.add(fc);
427                         break;
428                     }
429                 }
430             }
431         }
432     }
433 
434     /**
435      * Generate a class file for the proxy class.  This method drives the
436      * class file generation process.






437      */
438     private byte[] generateClassFile() {
439         /*
440          * Add proxy methods for the hashCode, equals,
441          * and toString methods of java.lang.Object.  This is done before
442          * the methods from the proxy interfaces so that the methods from
443          * java.lang.Object take precedence over duplicate methods in the
444          * proxy interfaces.
445          */
446         addProxyMethod(new ProxyMethod(OBJECT_HASH_CODE_METHOD, OBJECT_HASH_CODE_SIG, "m0"));
447         addProxyMethod(new ProxyMethod(OBJECT_EQUALS_METHOD, OBJECT_EQUALS_SIG, "m1"));
448         addProxyMethod(new ProxyMethod(OBJECT_TO_STRING_METHOD, OBJECT_TO_STRING_SIG, "m2"));
449 
450         /*
451          * Accumulate all of the methods from the proxy interfaces.
452          */
453         for (Class<?> intf : interfaces) {
454             for (Method m : intf.getMethods()) {
455                 if (!Modifier.isStatic(m.getModifiers())) {
456                     addProxyMethod(m, intf);
457                 }
458             }
459         }
460 
461         /*
462          * For each set of proxy methods with the same signature,
463          * verify that the methods' return types are compatible.
464          */
465         for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
466             checkReturnTypes(sigmethods);
467         }
468 
469         return CF_CONTEXT.build(thisClassCE, cp, clb -> {
470             clb.withSuperclass(proxyCE);
471             clb.withFlags(accessFlags);
472             clb.withInterfaces(toClassEntries(cp, interfaces));
473             generateConstructor(clb);
474 
475             for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
476                 for (ProxyMethod pm : sigmethods) {
477                     // add static field for the Method object
478                     clb.withField(pm.methodFieldName, CD_Method, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
479 
480                     // Generate code for proxy method
481                     pm.generateMethod(clb);
482                 }
483             }
484 
485             generateStaticInitializer(clb);
486             generateLookupAccessor(clb);
487         });
488     }
489 
490     /**
491      * Add another method to be proxied, either by creating a new
492      * ProxyMethod object or augmenting an old one for a duplicate
493      * method.
494      *
495      * "fromClass" indicates the proxy interface that the method was
496      * found through, which may be different from (a subinterface of)
497      * the method's "declaring class".  Note that the first Method
498      * object passed for a given name and descriptor identifies the
499      * Method object (and thus the declaring class) that will be
500      * passed to the invocation handler's "invoke" method for a given
501      * set of duplicate methods.
502      */
503     private void addProxyMethod(Method m, Class<?> fromClass) {
504         Class<?> returnType = m.getReturnType();
505         Class<?>[] exceptionTypes = m.getSharedExceptionTypes();
506 
507         String sig = m.toShortSignature();
508         List<ProxyMethod> sigmethods = proxyMethodsFor(sig);
509         for (ProxyMethod pm : sigmethods) {
510             if (returnType == pm.returnType) {
511                 /*
512                  * Found a match: reduce exception types to the
513                  * greatest set of exceptions that can be thrown
514                  * compatibly with the throws clauses of both
515                  * overridden methods.
516                  */
517                 List<Class<?>> legalExceptions = new ArrayList<>();
518                 collectCompatibleTypes(
519                         exceptionTypes, pm.exceptionTypes, legalExceptions);
520                 collectCompatibleTypes(
521                         pm.exceptionTypes, exceptionTypes, legalExceptions);
522                 pm.exceptionTypes = legalExceptions.toArray(EMPTY_CLASS_ARRAY);
523                 return;
524             }
525         }
526         sigmethods.add(new ProxyMethod(m, sig, returnType,
527                 exceptionTypes, fromClass, "m" + proxyMethodCount++));
528     }
529 
530     private List<ProxyMethod> proxyMethodsFor(String sig) {
531         return proxyMethods.computeIfAbsent(sig, _ -> new ArrayList<>(3));
532     }
533 
534     /**
535      * Add an existing ProxyMethod (hashcode, equals, toString).
536      *
537      * @param pm an existing ProxyMethod
538      */
539     private void addProxyMethod(ProxyMethod pm) {
540         proxyMethodsFor(pm.shortSignature).add(pm);
541     }
542 
543     /**
544      * Generate the constructor method for the proxy class.
545      */
546     private void generateConstructor(ClassBuilder clb) {
547         clb.withMethodBody(INIT_NAME, MTD_void_InvocationHandler, ACC_PUBLIC, cob -> cob
548                .aload(0)
549                .aload(1)
550                .invokespecial(cp.methodRefEntry(proxyCE,
551                    cp.nameAndTypeEntry(INIT_NAME, MTD_void_InvocationHandler)))
552                .return_());
553     }
554 
555     /**
556      * Generate the class initializer.
557      */
558     private void generateStaticInitializer(ClassBuilder clb) {
559         clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, cob -> {
560             // Put ClassLoader at local variable index 0, used by
561             // Class.forName(String, boolean, ClassLoader) calls
562             cob.ldc(thisClassCE)
563                .invokevirtual(cp.methodRefEntry(classCE,
564                        cp.nameAndTypeEntry("getClassLoader", MTD_ClassLoader)))
565                .astore(0);
566             var ts = cob.newBoundLabel();
567             for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
568                 for (ProxyMethod pm : sigmethods) {
569                     pm.codeFieldInitialization(cob);
570                 }
571             }
572             cob.return_();
573             var c1 = cob.newBoundLabel();
574             var nsmError = cp.classEntry(CD_NoSuchMethodError);
575             cob.exceptionCatch(ts, c1, c1, CD_NoSuchMethodException)
576                .new_(nsmError)
577                .dup_x1()
578                .swap()
579                .invokevirtual(throwableGetMessage)
580                .invokespecial(cp.methodRefEntry(nsmError, exInit))
581                .athrow();
582             var c2 = cob.newBoundLabel();
583             var ncdfError = cp.classEntry(CD_NoClassDefFoundError);
584             cob.exceptionCatch(ts, c1, c2, CD_ClassNotFoundException)
585                .new_(ncdfError)
586                .dup_x1()
587                .swap()
588                .invokevirtual(throwableGetMessage)
589                .invokespecial(cp.methodRefEntry(ncdfError, exInit))
590                .athrow();
591             cob.with(StackMapTableAttribute.of(List.of(
592                        StackMapFrameInfo.of(c1, classLoaderLocal, throwableStack),
593                        StackMapFrameInfo.of(c2, classLoaderLocal, throwableStack))));
594 
595         });
596     }
597 
598     /**
599      * Generate the static lookup accessor method that returns the Lookup
600      * on this proxy class if the caller's lookup class is java.lang.reflect.Proxy;
601      * otherwise, IllegalAccessException is thrown
602      */
603     private void generateLookupAccessor(ClassBuilder clb) {
604         clb.withMethod(NAME_LOOKUP_ACCESSOR,
605                 MTD_MethodHandles$Lookup_MethodHandles$Lookup,
606                 ACC_PRIVATE | ACC_STATIC,
607                 mb -> mb.with(ExceptionsAttribute.of(List.of(mb.constantPool().classEntry(CD_IllegalAccessException))))
608                         .withCode(cob -> {
609                             Label failLabel = cob.newLabel();
610                             ClassEntry mhl = cp.classEntry(CD_MethodHandles_Lookup);
611                             ClassEntry iae = cp.classEntry(CD_IllegalAccessException);
612                             cob.aload(0)
613                                .invokevirtual(cp.methodRefEntry(mhl, cp.nameAndTypeEntry("lookupClass", MTD_Class)))
614                                .ldc(proxyCE)
615                                .if_acmpne(failLabel)
616                                .aload(0)
617                                .invokevirtual(cp.methodRefEntry(mhl, cp.nameAndTypeEntry("hasFullPrivilegeAccess", MTD_boolean)))
618                                .ifeq(failLabel)
619                                .invokestatic(CD_MethodHandles, "lookup", MTD_MethodHandles$Lookup)
620                                .areturn()
621                                .labelBinding(failLabel)
622                                .new_(iae)
623                                .dup()
624                                .aload(0)
625                                .invokevirtual(cp.methodRefEntry(mhl, cp.nameAndTypeEntry("toString", MTD_String)))
626                                .invokespecial(cp.methodRefEntry(iae, exInit))
627                                .athrow()
628                                .with(StackMapTableAttribute.of(List.of(
629                                        StackMapFrameInfo.of(failLabel,
630                                                List.of(StackMapFrameInfo.ObjectVerificationTypeInfo.of(mhl)),
631                                                List.of()))));
632                         }));
633     }
634 
635     /**
636      * A ProxyMethod object represents a proxy method in the proxy class
637      * being generated: a method whose implementation will encode and
638      * dispatch invocations to the proxy instance's invocation handler.
639      */
640     private class ProxyMethod {
641 
642         private final Method method;
643         private final String shortSignature;
644         private final Class<?> fromClass;
645         private final Class<?> returnType;
646         private final String methodFieldName;
647         private Class<?>[] exceptionTypes;
648         private final FieldRefEntry methodField;
649 
650         private ProxyMethod(Method method, String sig,
651                             Class<?> returnType, Class<?>[] exceptionTypes,
652                             Class<?> fromClass, String methodFieldName) {
653             this.method = method;
654             this.shortSignature = sig;
655             this.returnType = returnType;
656             this.exceptionTypes = exceptionTypes;
657             this.fromClass = fromClass;
658             this.methodFieldName = methodFieldName;
659             this.methodField = cp.fieldRefEntry(thisClassCE,
660                 cp.nameAndTypeEntry(methodFieldName, CD_Method));
661         }
662 
663         private Class<?>[] parameterTypes() {
664             return method.getSharedParameterTypes();
665         }
666 
667         /**
668          * Create a new specific ProxyMethod with a specific field name
669          *
670          * @param method          The method for which to create a proxy
671          */
672         private ProxyMethod(Method method, String sig, String methodFieldName) {
673             this(method, sig, method.getReturnType(),
674                  method.getSharedExceptionTypes(), method.getDeclaringClass(), methodFieldName);
675         }
676 
677         /**
678          * Generate this method, including the code and exception table entry.
679          */
680         private void generateMethod(ClassBuilder clb) {
681             var desc = methodTypeDesc(returnType, parameterTypes());
682             int accessFlags = (method.isVarArgs()) ? ACC_VARARGS | ACC_PUBLIC | ACC_FINAL
683                                                    : ACC_PUBLIC | ACC_FINAL;
684             clb.withMethod(method.getName(), desc, accessFlags, mb ->
685                   mb.with(ExceptionsAttribute.of(toClassEntries(cp, List.of(exceptionTypes))))
686                     .withCode(cob -> {
687                         var catchList = computeUniqueCatchList(exceptionTypes);
688                         cob.aload(cob.receiverSlot())
689                            .getfield(handlerField)
690                            .aload(cob.receiverSlot())
691                            .getstatic(methodField);
692                         Class<?>[] parameterTypes = parameterTypes();
693                         if (parameterTypes.length > 0) {
694                             // Create an array and fill with the parameters converting primitives to wrappers
695                             cob.loadConstant(parameterTypes.length)
696                                .anewarray(objectCE);
697                             for (int i = 0; i < parameterTypes.length; i++) {
698                                 cob.dup()
699                                    .loadConstant(i);
700                                 codeWrapArgument(cob, parameterTypes[i], cob.parameterSlot(i));
701                                 cob.aastore();
702                             }
703                         } else {
704                             cob.aconst_null();
705                         }
706 
707                         cob.invokeinterface(invocationHandlerInvoke);
708 
709                         if (returnType == void.class) {
710                             cob.pop()
711                                .return_();
712                         } else {
713                             codeUnwrapReturnValue(cob, returnType);
714                         }
715                         if (!catchList.isEmpty()) {
716                             var c1 = cob.newBoundLabel();
717                             for (var exc : catchList) {
718                                 cob.exceptionCatch(cob.startLabel(), c1, c1, referenceClassDesc(exc));
719                             }
720                             cob.athrow();   // just rethrow the exception
721                             var c2 = cob.newBoundLabel();
722                             cob.exceptionCatchAll(cob.startLabel(), c1, c2)
723                                .new_(uteCE)
724                                .dup_x1()
725                                .swap()
726                                .invokespecial(uteInit)
727                                .athrow()
728                                .with(StackMapTableAttribute.of(List.of(
729                                     StackMapFrameInfo.of(c1, List.of(), throwableStack),
730                                     StackMapFrameInfo.of(c2, List.of(), throwableStack))));
731                         }
732                     }));
733         }
734 
735         /**
736          * Generate code for wrapping an argument of the given type
737          * whose value can be found at the specified local variable
738          * index, in order for it to be passed (as an Object) to the
739          * invocation handler's "invoke" method.
740          */
741         private void codeWrapArgument(CodeBuilder cob, Class<?> type, int slot) {
742             if (type.isPrimitive()) {
743                 cob.loadLocal(TypeKind.from(type).asLoadable(), slot);
744                 PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(type);
745                 cob.invokestatic(prim.wrapperMethodRef(cp));
746             } else {
747                 cob.aload(slot);
748             }
749         }
750 
751         /**
752          * Generate code for unwrapping a return value of the given
753          * type from the invocation handler's "invoke" method (as type
754          * Object) to its correct type.
755          */
756         private void codeUnwrapReturnValue(CodeBuilder cob, Class<?> type) {
757             if (type.isPrimitive()) {
758                 PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(type);
759 
760                 cob.checkcast(prim.wrapperClass)
761                    .invokevirtual(prim.unwrapMethodRef(cp))
762                    .return_(TypeKind.from(type).asLoadable());
763             } else {
764                 cob.checkcast(referenceClassDesc(type))
765                    .areturn();
766             }
767         }
768 
769         /**
770          * Generate code for initializing the static field that stores
771          * the Method object for this proxy method. A class loader is
772          * anticipated at local variable index 0.
773          */
774         private void codeFieldInitialization(CodeBuilder cob) {
775             var cp = cob.constantPool();
776             codeClassForName(cob, fromClass);
777 
778             Class<?>[] parameterTypes = parameterTypes();
779             cob.ldc(method.getName())
780                .loadConstant(parameterTypes.length)
781                .anewarray(classCE);
782 
783             // Construct an array with the parameter types mapping primitives to Wrapper types
784             for (int i = 0; i < parameterTypes.length; i++) {
785                 cob.dup()
786                    .loadConstant(i);
787                 if (parameterTypes[i].isPrimitive()) {
788                     PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(parameterTypes[i]);
789                     cob.getstatic(prim.typeFieldRef(cp));
790                 } else {
791                     codeClassForName(cob, parameterTypes[i]);
792                 }
793                 cob.aastore();
794             }
795             // lookup the method
796             cob.invokevirtual(classGetMethod)
797                .putstatic(methodField);
798         }
799 
800         /*
801          * =============== Code Generation Utility Methods ===============
802          */
803 
804         /**
805          * Generate code to invoke the Class.forName with the name of the given
806          * class to get its Class object at runtime.  The code is written to
807          * the supplied stream.  Note that the code generated by this method
808          * may cause the checked ClassNotFoundException to be thrown. A class
809          * loader is anticipated at local variable index 0.
810          */
811         private void codeClassForName(CodeBuilder cob, Class<?> cl) {
812             if (cl == Object.class) {
813                 cob.ldc(objectCE);
814             } else {
815                 cob.ldc(cl.getName())
816                         .iconst_0() // false
817                         .aload(0)// classLoader
818                         .invokestatic(classForName);
819             }
820         }
821 
822         @Override
823         public String toString() {
824             return method.toShortString();
825         }
826     }
827 
828     /**
829      * A PrimitiveTypeInfo object contains bytecode-related information about
830      * a primitive type in its instance fields. The struct for a particular
831      * primitive type can be obtained using the static "get" method.
832      */
833     private enum PrimitiveTypeInfo {
834         BYTE(byte.class, CD_byte, CD_Byte),
835         CHAR(char.class, CD_char, CD_Character),
836         DOUBLE(double.class, CD_double, CD_Double),
837         FLOAT(float.class, CD_float, CD_Float),
838         INT(int.class, CD_int, CD_Integer),
839         LONG(long.class, CD_long, CD_Long),
840         SHORT(short.class, CD_short, CD_Short),
841         BOOLEAN(boolean.class, CD_boolean, CD_Boolean);
842 
843         /**
844          * wrapper class
845          */
846         private final ClassDesc wrapperClass;
847         /**
848          * wrapper factory method type
849          */
850         private final MethodTypeDesc wrapperMethodType;
851         /**
852          * wrapper class method name for retrieving primitive value
853          */
854         private final String unwrapMethodName;
855         /**
856          * wrapper class method type for retrieving primitive value
857          */
858         private final MethodTypeDesc unwrapMethodType;
859 
860         PrimitiveTypeInfo(Class<?> primitiveClass, ClassDesc baseType, ClassDesc wrapperClass) {
861             assert baseType.isPrimitive();
862             this.wrapperClass = wrapperClass;
863             this.wrapperMethodType = MethodTypeDescImpl.ofValidated(wrapperClass, baseType);
864             this.unwrapMethodName = primitiveClass.getName() + "Value";
865             this.unwrapMethodType = MethodTypeDescImpl.ofValidated(baseType);
866         }
867 
868         public static PrimitiveTypeInfo get(Class<?> cl) {
869             // Uses if chain for speed: 8284880
870             if (cl == int.class)     return INT;
871             if (cl == long.class)    return LONG;
872             if (cl == boolean.class) return BOOLEAN;
873             if (cl == short.class)   return SHORT;
874             if (cl == byte.class)    return BYTE;
875             if (cl == char.class)    return CHAR;
876             if (cl == float.class)   return FLOAT;
877             if (cl == double.class)  return DOUBLE;
878             throw new AssertionError(cl);
879         }
880 
881         public MethodRefEntry wrapperMethodRef(ConstantPoolBuilder cp) {
882             return cp.methodRefEntry(wrapperClass, "valueOf", wrapperMethodType);
883         }
884 
885         public MethodRefEntry unwrapMethodRef(ConstantPoolBuilder cp) {
886             return cp.methodRefEntry(wrapperClass, unwrapMethodName, unwrapMethodType);
887         }
888 
889         public FieldRefEntry typeFieldRef(ConstantPoolBuilder cp) {
890             return cp.fieldRefEntry(wrapperClass, "TYPE", CD_Class);
891         }
892     }
893 }
--- EOF ---