1 /* 2 * Copyright (c) 1999, 2024, 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 import jdk.internal.constant.ConstantUtils; 43 import jdk.internal.constant.MethodTypeDescImpl; 44 import jdk.internal.constant.ReferenceClassDescImpl; 45 import sun.security.action.GetBooleanAction; 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 = ReferenceClassDescImpl.ofValidated("Ljava/lang/ClassLoader;"), 68 CD_Class_array = ReferenceClassDescImpl.ofValidated("[Ljava/lang/Class;"), 69 CD_ClassNotFoundException = ReferenceClassDescImpl.ofValidated("Ljava/lang/ClassNotFoundException;"), 70 CD_NoClassDefFoundError = ReferenceClassDescImpl.ofValidated("Ljava/lang/NoClassDefFoundError;"), 71 CD_IllegalAccessException = ReferenceClassDescImpl.ofValidated("Ljava/lang/IllegalAccessException;"), 72 CD_InvocationHandler = ReferenceClassDescImpl.ofValidated("Ljava/lang/reflect/InvocationHandler;"), 73 CD_Method = ReferenceClassDescImpl.ofValidated("Ljava/lang/reflect/Method;"), 74 CD_NoSuchMethodError = ReferenceClassDescImpl.ofValidated("Ljava/lang/NoSuchMethodError;"), 75 CD_NoSuchMethodException = ReferenceClassDescImpl.ofValidated("Ljava/lang/NoSuchMethodException;"), 76 CD_Object_array = ReferenceClassDescImpl.ofValidated("[Ljava/lang/Object;"), 77 CD_Proxy = ReferenceClassDescImpl.ofValidated("Ljava/lang/reflect/Proxy;"), 78 CD_UndeclaredThrowableException = ReferenceClassDescImpl.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 @SuppressWarnings("removal") 107 private static final boolean SAVE_GENERATED_FILES = 108 java.security.AccessController.doPrivileged( 109 new GetBooleanAction( 110 "jdk.proxy.ProxyGenerator.saveGeneratedFiles")); 111 112 /* Preloaded ProxyMethod objects for methods in java.lang.Object */ 113 private static final Method OBJECT_HASH_CODE_METHOD; 114 private static final Method OBJECT_EQUALS_METHOD; 115 private static final Method OBJECT_TO_STRING_METHOD; 116 117 private static final String OBJECT_HASH_CODE_SIG; 118 private static final String OBJECT_EQUALS_SIG; 119 private static final String OBJECT_TO_STRING_SIG; 120 121 static { 122 try { 123 OBJECT_HASH_CODE_METHOD = Object.class.getMethod("hashCode"); 124 OBJECT_HASH_CODE_SIG = OBJECT_HASH_CODE_METHOD.toShortSignature(); 125 OBJECT_EQUALS_METHOD = Object.class.getMethod("equals", Object.class); 126 OBJECT_EQUALS_SIG = OBJECT_EQUALS_METHOD.toShortSignature(); 127 OBJECT_TO_STRING_METHOD = Object.class.getMethod("toString"); 128 OBJECT_TO_STRING_SIG = OBJECT_TO_STRING_METHOD.toShortSignature(); 129 } catch (NoSuchMethodException e) { 130 throw new NoSuchMethodError(e.getMessage()); 131 } 132 } 133 134 private final ConstantPoolBuilder cp; 135 private final List<StackMapFrameInfo.VerificationTypeInfo> classLoaderLocal, throwableStack; 136 private final NameAndTypeEntry exInit; 137 private final ClassEntry objectCE, proxyCE, uteCE, classCE; 138 private final FieldRefEntry handlerField; 139 private final InterfaceMethodRefEntry invocationHandlerInvoke; 140 private final MethodRefEntry uteInit, classGetMethod, classForName, throwableGetMessage; 141 142 143 /** 144 * ClassEntry for this proxy class 145 */ 146 private final ClassEntry thisClassCE; 147 148 /** 149 * Proxy interfaces 150 */ 151 private final List<Class<?>> interfaces; 152 153 /** 154 * Proxy class access flags 155 */ 156 private final int accessFlags; 157 158 /** 159 * Maps method signature string to list of ProxyMethod objects for 160 * proxy methods with that signature. 161 * Kept in insertion order to make it easier to compare old and new. 162 */ 163 private final Map<String, List<ProxyMethod>> proxyMethods = new LinkedHashMap<>(); 164 165 /** 166 * Ordinal of next ProxyMethod object added to proxyMethods. 167 * Indexes are reserved for hashcode(0), equals(1), toString(2). 168 */ 169 private int proxyMethodCount = 3; 170 171 /** 172 * Construct a ProxyGenerator to generate a proxy class with the 173 * specified name and for the given interfaces. 174 * <p> 175 * A ProxyGenerator object contains the state for the ongoing 176 * generation of a particular proxy class. 177 */ 178 private ProxyGenerator(String className, List<Class<?>> interfaces, 179 int accessFlags) { 180 this.cp = ConstantPoolBuilder.of(); 181 this.thisClassCE = cp.classEntry(ConstantUtils.binaryNameToDesc(className)); 182 this.interfaces = interfaces; 183 this.accessFlags = accessFlags; 184 var throwable = cp.classEntry(CD_Throwable); 185 this.classLoaderLocal = List.of(StackMapFrameInfo.ObjectVerificationTypeInfo.of(cp.classEntry(CD_ClassLoader))); 186 this.throwableStack = List.of(StackMapFrameInfo.ObjectVerificationTypeInfo.of(throwable)); 187 this.exInit = cp.nameAndTypeEntry(INIT_NAME, MTD_void_String); 188 this.objectCE = cp.classEntry(CD_Object); 189 this.proxyCE = cp.classEntry(CD_Proxy); 190 this.classCE = cp.classEntry(CD_Class); 191 this.handlerField = cp.fieldRefEntry(proxyCE, cp.nameAndTypeEntry(NAME_HANDLER_FIELD, CD_InvocationHandler)); 192 this.invocationHandlerInvoke = cp.interfaceMethodRefEntry(CD_InvocationHandler, "invoke", MTD_Object_Object_Method_ObjectArray); 193 this.uteCE = cp.classEntry(CD_UndeclaredThrowableException); 194 this.uteInit = cp.methodRefEntry(uteCE, cp.nameAndTypeEntry(INIT_NAME, MTD_void_Throwable)); 195 this.classGetMethod = cp.methodRefEntry(classCE, cp.nameAndTypeEntry("getMethod", MTD_Method_String_Class_array)); 196 this.classForName = cp.methodRefEntry(classCE, cp.nameAndTypeEntry("forName", MTD_Class_String_boolean_ClassLoader)); 197 this.throwableGetMessage = cp.methodRefEntry(throwable, cp.nameAndTypeEntry("getMessage", MTD_String)); 198 } 199 200 /** 201 * Generate a proxy class given a name and a list of proxy interfaces. 202 * 203 * @param name the class name of the proxy class 204 * @param interfaces proxy interfaces 205 * @param accessFlags access flags of the proxy class 206 */ 207 @SuppressWarnings("removal") 208 static byte[] generateProxyClass(ClassLoader loader, 209 final String name, 210 List<Class<?>> interfaces, 211 int accessFlags) { 212 Objects.requireNonNull(interfaces); 213 ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags); 214 final byte[] classFile = gen.generateClassFile(); 215 216 if (SAVE_GENERATED_FILES) { 217 java.security.AccessController.doPrivileged( 218 new java.security.PrivilegedAction<Void>() { 219 public Void run() { 220 try { 221 int i = name.lastIndexOf('.'); 222 Path path; 223 if (i > 0) { 224 Path dir = Path.of(name.substring(0, i).replace('.', '/')); 225 Files.createDirectories(dir); 226 path = dir.resolve(name.substring(i + 1) + ".class"); 227 } else { 228 path = Path.of(name + ".class"); 229 } 230 Files.write(path, classFile); 231 return null; 232 } catch (IOException e) { 233 throw new InternalError( 234 "I/O exception saving generated file: " + e); 235 } 236 } 237 }); 238 } 239 240 return classFile; 241 } 242 243 /** 244 * {@return the entries of the given type} 245 * @param types the {@code Class} objects, not primitive types nor array types 246 */ 247 private static List<ClassEntry> toClassEntries(ConstantPoolBuilder cp, List<Class<?>> types) { 248 var ces = new ArrayList<ClassEntry>(types.size()); 249 for (var t : types) 250 ces.add(cp.classEntry(ConstantUtils.binaryNameToDesc(t.getName()))); 251 return ces; 252 } 253 254 /** 255 * For a given set of proxy methods with the same signature, check 256 * that their return types are compatible according to the Proxy 257 * specification. 258 * 259 * Specifically, if there is more than one such method, then all 260 * of the return types must be reference types, and there must be 261 * one return type that is assignable to each of the rest of them. 262 */ 263 private static void checkReturnTypes(List<ProxyMethod> methods) { 264 /* 265 * If there is only one method with a given signature, there 266 * cannot be a conflict. This is the only case in which a 267 * primitive (or void) return type is allowed. 268 */ 269 if (methods.size() < 2) { 270 return; 271 } 272 273 /* 274 * List of return types that are not yet known to be 275 * assignable from ("covered" by) any of the others. 276 */ 277 List<Class<?>> uncoveredReturnTypes = new ArrayList<>(1); 278 279 nextNewReturnType: 280 for (ProxyMethod pm : methods) { 281 Class<?> newReturnType = pm.returnType; 282 if (newReturnType.isPrimitive()) { 283 throw new IllegalArgumentException( 284 "methods with same signature " + 285 pm.shortSignature + 286 " but incompatible return types: " + 287 newReturnType.getName() + " and others"); 288 } 289 boolean added = false; 290 291 /* 292 * Compare the new return type to the existing uncovered 293 * return types. 294 */ 295 ListIterator<Class<?>> liter = uncoveredReturnTypes.listIterator(); 296 while (liter.hasNext()) { 297 Class<?> uncoveredReturnType = liter.next(); 298 299 /* 300 * If an existing uncovered return type is assignable 301 * to this new one, then we can forget the new one. 302 */ 303 if (newReturnType.isAssignableFrom(uncoveredReturnType)) { 304 assert !added; 305 continue nextNewReturnType; 306 } 307 308 /* 309 * If the new return type is assignable to an existing 310 * uncovered one, then should replace the existing one 311 * with the new one (or just forget the existing one, 312 * if the new one has already be put in the list). 313 */ 314 if (uncoveredReturnType.isAssignableFrom(newReturnType)) { 315 // (we can assume that each return type is unique) 316 if (!added) { 317 liter.set(newReturnType); 318 added = true; 319 } else { 320 liter.remove(); 321 } 322 } 323 } 324 325 /* 326 * If we got through the list of existing uncovered return 327 * types without an assignability relationship, then add 328 * the new return type to the list of uncovered ones. 329 */ 330 if (!added) { 331 uncoveredReturnTypes.add(newReturnType); 332 } 333 } 334 335 /* 336 * We shouldn't end up with more than one return type that is 337 * not assignable from any of the others. 338 */ 339 if (uncoveredReturnTypes.size() > 1) { 340 ProxyMethod pm = methods.getFirst(); 341 throw new IllegalArgumentException( 342 "methods with same signature " + 343 pm.shortSignature + 344 " but incompatible return types: " + uncoveredReturnTypes); 345 } 346 } 347 348 /** 349 * Given the exceptions declared in the throws clause of a proxy method, 350 * compute the exceptions that need to be caught from the invocation 351 * handler's invoke method and rethrown intact in the method's 352 * implementation before catching other Throwables and wrapping them 353 * in UndeclaredThrowableExceptions. 354 * 355 * The exceptions to be caught are returned in a List object. Each 356 * exception in the returned list is guaranteed to not be a subclass of 357 * any of the other exceptions in the list, so the catch blocks for 358 * these exceptions may be generated in any order relative to each other. 359 * 360 * Error and RuntimeException are each always contained by the returned 361 * list (if none of their superclasses are contained), since those 362 * unchecked exceptions should always be rethrown intact, and thus their 363 * subclasses will never appear in the returned list. 364 * 365 * The returned List will be empty if java.lang.Throwable is in the 366 * given list of declared exceptions, indicating that no exceptions 367 * need to be caught. 368 */ 369 private static List<Class<?>> computeUniqueCatchList(Class<?>[] exceptions) { 370 List<Class<?>> uniqueList = new ArrayList<>(); 371 // unique exceptions to catch 372 373 uniqueList.add(Error.class); // always catch/rethrow these 374 uniqueList.add(RuntimeException.class); 375 376 nextException: 377 for (Class<?> ex : exceptions) { 378 if (ex.isAssignableFrom(Throwable.class)) { 379 /* 380 * If Throwable is declared to be thrown by the proxy method, 381 * then no catch blocks are necessary, because the invoke 382 * can, at most, throw Throwable anyway. 383 */ 384 uniqueList.clear(); 385 break; 386 } else if (!Throwable.class.isAssignableFrom(ex)) { 387 /* 388 * Ignore types that cannot be thrown by the invoke method. 389 */ 390 continue; 391 } 392 /* 393 * Compare this exception against the current list of 394 * exceptions that need to be caught: 395 */ 396 for (int j = 0; j < uniqueList.size(); ) { 397 Class<?> ex2 = uniqueList.get(j); 398 if (ex2.isAssignableFrom(ex)) { 399 /* 400 * if a superclass of this exception is already on 401 * the list to catch, then ignore this one and continue; 402 */ 403 continue nextException; 404 } else if (ex.isAssignableFrom(ex2)) { 405 /* 406 * if a subclass of this exception is on the list 407 * to catch, then remove it; 408 */ 409 uniqueList.remove(j); 410 } else { 411 j++; // else continue comparing. 412 } 413 } 414 // This exception is unique (so far): add it to the list to catch. 415 uniqueList.add(ex); 416 } 417 return uniqueList; 418 } 419 420 /** 421 * Add to the given list all of the types in the "from" array that 422 * are not already contained in the list and are assignable to at 423 * least one of the types in the "with" array. 424 * <p> 425 * This method is useful for computing the greatest common set of 426 * declared exceptions from duplicate methods inherited from 427 * different interfaces. 428 */ 429 private static void collectCompatibleTypes(Class<?>[] from, 430 Class<?>[] with, 431 List<Class<?>> list) { 432 for (Class<?> fc : from) { 433 if (!list.contains(fc)) { 434 for (Class<?> wc : with) { 435 if (wc.isAssignableFrom(fc)) { 436 list.add(fc); 437 break; 438 } 439 } 440 } 441 } 442 } 443 444 /** 445 * Generate a class file for the proxy class. This method drives the 446 * class file generation process. 447 */ 448 private byte[] generateClassFile() { 449 /* 450 * Add proxy methods for the hashCode, equals, 451 * and toString methods of java.lang.Object. This is done before 452 * the methods from the proxy interfaces so that the methods from 453 * java.lang.Object take precedence over duplicate methods in the 454 * proxy interfaces. 455 */ 456 addProxyMethod(new ProxyMethod(OBJECT_HASH_CODE_METHOD, OBJECT_HASH_CODE_SIG, "m0")); 457 addProxyMethod(new ProxyMethod(OBJECT_EQUALS_METHOD, OBJECT_EQUALS_SIG, "m1")); 458 addProxyMethod(new ProxyMethod(OBJECT_TO_STRING_METHOD, OBJECT_TO_STRING_SIG, "m2")); 459 460 /* 461 * Accumulate all of the methods from the proxy interfaces. 462 */ 463 for (Class<?> intf : interfaces) { 464 for (Method m : intf.getMethods()) { 465 if (!Modifier.isStatic(m.getModifiers())) { 466 addProxyMethod(m, intf); 467 } 468 } 469 } 470 471 /* 472 * For each set of proxy methods with the same signature, 473 * verify that the methods' return types are compatible. 474 */ 475 for (List<ProxyMethod> sigmethods : proxyMethods.values()) { 476 checkReturnTypes(sigmethods); 477 } 478 479 return CF_CONTEXT.build(thisClassCE, cp, clb -> { 480 clb.withSuperclass(proxyCE); 481 clb.withFlags(accessFlags); 482 clb.withInterfaces(toClassEntries(cp, interfaces)); 483 generateConstructor(clb); 484 485 for (List<ProxyMethod> sigmethods : proxyMethods.values()) { 486 for (ProxyMethod pm : sigmethods) { 487 // add static field for the Method object 488 clb.withField(pm.methodFieldName, CD_Method, ACC_PRIVATE | ACC_STATIC | ACC_FINAL); 489 490 // Generate code for proxy method 491 pm.generateMethod(clb); 492 } 493 } 494 495 generateStaticInitializer(clb); 496 generateLookupAccessor(clb); 497 }); 498 } 499 500 /** 501 * Add another method to be proxied, either by creating a new 502 * ProxyMethod object or augmenting an old one for a duplicate 503 * method. 504 * 505 * "fromClass" indicates the proxy interface that the method was 506 * found through, which may be different from (a subinterface of) 507 * the method's "declaring class". Note that the first Method 508 * object passed for a given name and descriptor identifies the 509 * Method object (and thus the declaring class) that will be 510 * passed to the invocation handler's "invoke" method for a given 511 * set of duplicate methods. 512 */ 513 private void addProxyMethod(Method m, Class<?> fromClass) { 514 Class<?> returnType = m.getReturnType(); 515 Class<?>[] exceptionTypes = m.getSharedExceptionTypes(); 516 517 String sig = m.toShortSignature(); 518 List<ProxyMethod> sigmethods = proxyMethodsFor(sig); 519 for (ProxyMethod pm : sigmethods) { 520 if (returnType == pm.returnType) { 521 /* 522 * Found a match: reduce exception types to the 523 * greatest set of exceptions that can be thrown 524 * compatibly with the throws clauses of both 525 * overridden methods. 526 */ 527 List<Class<?>> legalExceptions = new ArrayList<>(); 528 collectCompatibleTypes( 529 exceptionTypes, pm.exceptionTypes, legalExceptions); 530 collectCompatibleTypes( 531 pm.exceptionTypes, exceptionTypes, legalExceptions); 532 pm.exceptionTypes = legalExceptions.toArray(EMPTY_CLASS_ARRAY); 533 return; 534 } 535 } 536 sigmethods.add(new ProxyMethod(m, sig, returnType, 537 exceptionTypes, fromClass, "m" + proxyMethodCount++)); 538 } 539 540 private List<ProxyMethod> proxyMethodsFor(String sig) { 541 return proxyMethods.computeIfAbsent(sig, _ -> new ArrayList<>(3)); 542 } 543 544 /** 545 * Add an existing ProxyMethod (hashcode, equals, toString). 546 * 547 * @param pm an existing ProxyMethod 548 */ 549 private void addProxyMethod(ProxyMethod pm) { 550 proxyMethodsFor(pm.shortSignature).add(pm); 551 } 552 553 /** 554 * Generate the constructor method for the proxy class. 555 */ 556 private void generateConstructor(ClassBuilder clb) { 557 clb.withMethodBody(INIT_NAME, MTD_void_InvocationHandler, ACC_PUBLIC, cob -> cob 558 .aload(0) 559 .aload(1) 560 .invokespecial(cp.methodRefEntry(proxyCE, 561 cp.nameAndTypeEntry(INIT_NAME, MTD_void_InvocationHandler))) 562 .return_()); 563 } 564 565 /** 566 * Generate the class initializer. 567 * Discussion: Currently, for Proxy to work with SecurityManager, 568 * we rely on the parameter classes of the methods to be computed 569 * from Proxy instead of via user code paths like bootstrap method 570 * lazy evaluation. That might change if we can pass in the live 571 * Method objects directly.. 572 */ 573 private void generateStaticInitializer(ClassBuilder clb) { 574 clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, cob -> { 575 // Put ClassLoader at local variable index 0, used by 576 // Class.forName(String, boolean, ClassLoader) calls 577 cob.ldc(thisClassCE) 578 .invokevirtual(cp.methodRefEntry(classCE, 579 cp.nameAndTypeEntry("getClassLoader", MTD_ClassLoader))) 580 .astore(0); 581 var ts = cob.newBoundLabel(); 582 for (List<ProxyMethod> sigmethods : proxyMethods.values()) { 583 for (ProxyMethod pm : sigmethods) { 584 pm.codeFieldInitialization(cob); 585 } 586 } 587 cob.return_(); 588 var c1 = cob.newBoundLabel(); 589 var nsmError = cp.classEntry(CD_NoSuchMethodError); 590 cob.exceptionCatch(ts, c1, c1, CD_NoSuchMethodException) 591 .new_(nsmError) 592 .dup_x1() 593 .swap() 594 .invokevirtual(throwableGetMessage) 595 .invokespecial(cp.methodRefEntry(nsmError, exInit)) 596 .athrow(); 597 var c2 = cob.newBoundLabel(); 598 var ncdfError = cp.classEntry(CD_NoClassDefFoundError); 599 cob.exceptionCatch(ts, c1, c2, CD_ClassNotFoundException) 600 .new_(ncdfError) 601 .dup_x1() 602 .swap() 603 .invokevirtual(throwableGetMessage) 604 .invokespecial(cp.methodRefEntry(ncdfError, exInit)) 605 .athrow(); 606 cob.with(StackMapTableAttribute.of(List.of( 607 StackMapFrameInfo.of(c1, classLoaderLocal, throwableStack), 608 StackMapFrameInfo.of(c2, classLoaderLocal, throwableStack)))); 609 610 }); 611 } 612 613 /** 614 * Generate the static lookup accessor method that returns the Lookup 615 * on this proxy class if the caller's lookup class is java.lang.reflect.Proxy; 616 * otherwise, IllegalAccessException is thrown 617 */ 618 private void generateLookupAccessor(ClassBuilder clb) { 619 clb.withMethod(NAME_LOOKUP_ACCESSOR, 620 MTD_MethodHandles$Lookup_MethodHandles$Lookup, 621 ACC_PRIVATE | ACC_STATIC, 622 mb -> mb.with(ExceptionsAttribute.of(List.of(mb.constantPool().classEntry(CD_IllegalAccessException)))) 623 .withCode(cob -> { 624 Label failLabel = cob.newLabel(); 625 ClassEntry mhl = cp.classEntry(CD_MethodHandles_Lookup); 626 ClassEntry iae = cp.classEntry(CD_IllegalAccessException); 627 cob.aload(0) 628 .invokevirtual(cp.methodRefEntry(mhl, cp.nameAndTypeEntry("lookupClass", MTD_Class))) 629 .ldc(proxyCE) 630 .if_acmpne(failLabel) 631 .aload(0) 632 .invokevirtual(cp.methodRefEntry(mhl, cp.nameAndTypeEntry("hasFullPrivilegeAccess", MTD_boolean))) 633 .ifeq(failLabel) 634 .invokestatic(CD_MethodHandles, "lookup", MTD_MethodHandles$Lookup) 635 .areturn() 636 .labelBinding(failLabel) 637 .new_(iae) 638 .dup() 639 .aload(0) 640 .invokevirtual(cp.methodRefEntry(mhl, cp.nameAndTypeEntry("toString", MTD_String))) 641 .invokespecial(cp.methodRefEntry(iae, exInit)) 642 .athrow() 643 .with(StackMapTableAttribute.of(List.of( 644 StackMapFrameInfo.of(failLabel, 645 List.of(StackMapFrameInfo.ObjectVerificationTypeInfo.of(mhl)), 646 List.of())))); 647 })); 648 } 649 650 /** 651 * A ProxyMethod object represents a proxy method in the proxy class 652 * being generated: a method whose implementation will encode and 653 * dispatch invocations to the proxy instance's invocation handler. 654 */ 655 private class ProxyMethod { 656 657 private final Method method; 658 private final String shortSignature; 659 private final Class<?> fromClass; 660 private final Class<?> returnType; 661 private final String methodFieldName; 662 private Class<?>[] exceptionTypes; 663 private final FieldRefEntry methodField; 664 665 private ProxyMethod(Method method, String sig, 666 Class<?> returnType, Class<?>[] exceptionTypes, 667 Class<?> fromClass, String methodFieldName) { 668 this.method = method; 669 this.shortSignature = sig; 670 this.returnType = returnType; 671 this.exceptionTypes = exceptionTypes; 672 this.fromClass = fromClass; 673 this.methodFieldName = methodFieldName; 674 this.methodField = cp.fieldRefEntry(thisClassCE, 675 cp.nameAndTypeEntry(methodFieldName, CD_Method)); 676 } 677 678 private Class<?>[] parameterTypes() { 679 return method.getSharedParameterTypes(); 680 } 681 682 /** 683 * Create a new specific ProxyMethod with a specific field name 684 * 685 * @param method The method for which to create a proxy 686 */ 687 private ProxyMethod(Method method, String sig, String methodFieldName) { 688 this(method, sig, method.getReturnType(), 689 method.getSharedExceptionTypes(), method.getDeclaringClass(), methodFieldName); 690 } 691 692 /** 693 * Generate this method, including the code and exception table entry. 694 */ 695 private void generateMethod(ClassBuilder clb) { 696 var desc = methodTypeDesc(returnType, parameterTypes()); 697 int accessFlags = (method.isVarArgs()) ? ACC_VARARGS | ACC_PUBLIC | ACC_FINAL 698 : ACC_PUBLIC | ACC_FINAL; 699 clb.withMethod(method.getName(), desc, accessFlags, mb -> 700 mb.with(ExceptionsAttribute.of(toClassEntries(cp, List.of(exceptionTypes)))) 701 .withCode(cob -> { 702 var catchList = computeUniqueCatchList(exceptionTypes); 703 cob.aload(cob.receiverSlot()) 704 .getfield(handlerField) 705 .aload(cob.receiverSlot()) 706 .getstatic(methodField); 707 Class<?>[] parameterTypes = parameterTypes(); 708 if (parameterTypes.length > 0) { 709 // Create an array and fill with the parameters converting primitives to wrappers 710 cob.loadConstant(parameterTypes.length) 711 .anewarray(objectCE); 712 for (int i = 0; i < parameterTypes.length; i++) { 713 cob.dup() 714 .loadConstant(i); 715 codeWrapArgument(cob, parameterTypes[i], cob.parameterSlot(i)); 716 cob.aastore(); 717 } 718 } else { 719 cob.aconst_null(); 720 } 721 722 cob.invokeinterface(invocationHandlerInvoke); 723 724 if (returnType == void.class) { 725 cob.pop() 726 .return_(); 727 } else { 728 codeUnwrapReturnValue(cob, returnType); 729 } 730 if (!catchList.isEmpty()) { 731 var c1 = cob.newBoundLabel(); 732 for (var exc : catchList) { 733 cob.exceptionCatch(cob.startLabel(), c1, c1, referenceClassDesc(exc)); 734 } 735 cob.athrow(); // just rethrow the exception 736 var c2 = cob.newBoundLabel(); 737 cob.exceptionCatchAll(cob.startLabel(), c1, c2) 738 .new_(uteCE) 739 .dup_x1() 740 .swap() 741 .invokespecial(uteInit) 742 .athrow() 743 .with(StackMapTableAttribute.of(List.of( 744 StackMapFrameInfo.of(c1, List.of(), throwableStack), 745 StackMapFrameInfo.of(c2, List.of(), throwableStack)))); 746 } 747 })); 748 } 749 750 /** 751 * Generate code for wrapping an argument of the given type 752 * whose value can be found at the specified local variable 753 * index, in order for it to be passed (as an Object) to the 754 * invocation handler's "invoke" method. 755 */ 756 private void codeWrapArgument(CodeBuilder cob, Class<?> type, int slot) { 757 if (type.isPrimitive()) { 758 cob.loadLocal(TypeKind.from(type).asLoadable(), slot); 759 PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(type); 760 cob.invokestatic(prim.wrapperMethodRef(cp)); 761 } else { 762 cob.aload(slot); 763 } 764 } 765 766 /** 767 * Generate code for unwrapping a return value of the given 768 * type from the invocation handler's "invoke" method (as type 769 * Object) to its correct type. 770 */ 771 private void codeUnwrapReturnValue(CodeBuilder cob, Class<?> type) { 772 if (type.isPrimitive()) { 773 PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(type); 774 775 cob.checkcast(prim.wrapperClass) 776 .invokevirtual(prim.unwrapMethodRef(cp)) 777 .return_(TypeKind.from(type).asLoadable()); 778 } else { 779 cob.checkcast(referenceClassDesc(type)) 780 .areturn(); 781 } 782 } 783 784 /** 785 * Generate code for initializing the static field that stores 786 * the Method object for this proxy method. A class loader is 787 * anticipated at local variable index 0. 788 * The generated code must be run in an AccessController.doPrivileged 789 * block if a SecurityManager is present, as otherwise the code 790 * cannot pass {@code null} ClassLoader to forName. 791 */ 792 private void codeFieldInitialization(CodeBuilder cob) { 793 var cp = cob.constantPool(); 794 codeClassForName(cob, fromClass); 795 796 Class<?>[] parameterTypes = parameterTypes(); 797 cob.ldc(method.getName()) 798 .loadConstant(parameterTypes.length) 799 .anewarray(classCE); 800 801 // Construct an array with the parameter types mapping primitives to Wrapper types 802 for (int i = 0; i < parameterTypes.length; i++) { 803 cob.dup() 804 .loadConstant(i); 805 if (parameterTypes[i].isPrimitive()) { 806 PrimitiveTypeInfo prim = PrimitiveTypeInfo.get(parameterTypes[i]); 807 cob.getstatic(prim.typeFieldRef(cp)); 808 } else { 809 codeClassForName(cob, parameterTypes[i]); 810 } 811 cob.aastore(); 812 } 813 // lookup the method 814 cob.invokevirtual(classGetMethod) 815 .putstatic(methodField); 816 } 817 818 /* 819 * =============== Code Generation Utility Methods =============== 820 */ 821 822 /** 823 * Generate code to invoke the Class.forName with the name of the given 824 * class to get its Class object at runtime. The code is written to 825 * the supplied stream. Note that the code generated by this method 826 * may cause the checked ClassNotFoundException to be thrown. A class 827 * loader is anticipated at local variable index 0. 828 */ 829 private void codeClassForName(CodeBuilder cob, Class<?> cl) { 830 if (cl == Object.class) { 831 cob.ldc(objectCE); 832 } else { 833 cob.ldc(cl.getName()) 834 .iconst_0() // false 835 .aload(0)// classLoader 836 .invokestatic(classForName); 837 } 838 } 839 840 @Override 841 public String toString() { 842 return method.toShortString(); 843 } 844 } 845 846 /** 847 * A PrimitiveTypeInfo object contains bytecode-related information about 848 * a primitive type in its instance fields. The struct for a particular 849 * primitive type can be obtained using the static "get" method. 850 */ 851 private enum PrimitiveTypeInfo { 852 BYTE(byte.class, CD_byte, CD_Byte), 853 CHAR(char.class, CD_char, CD_Character), 854 DOUBLE(double.class, CD_double, CD_Double), 855 FLOAT(float.class, CD_float, CD_Float), 856 INT(int.class, CD_int, CD_Integer), 857 LONG(long.class, CD_long, CD_Long), 858 SHORT(short.class, CD_short, CD_Short), 859 BOOLEAN(boolean.class, CD_boolean, CD_Boolean); 860 861 /** 862 * wrapper class 863 */ 864 private final ClassDesc wrapperClass; 865 /** 866 * wrapper factory method type 867 */ 868 private final MethodTypeDesc wrapperMethodType; 869 /** 870 * wrapper class method name for retrieving primitive value 871 */ 872 private final String unwrapMethodName; 873 /** 874 * wrapper class method type for retrieving primitive value 875 */ 876 private final MethodTypeDesc unwrapMethodType; 877 878 PrimitiveTypeInfo(Class<?> primitiveClass, ClassDesc baseType, ClassDesc wrapperClass) { 879 assert baseType.isPrimitive(); 880 this.wrapperClass = wrapperClass; 881 this.wrapperMethodType = MethodTypeDescImpl.ofValidated(wrapperClass, baseType); 882 this.unwrapMethodName = primitiveClass.getName() + "Value"; 883 this.unwrapMethodType = MethodTypeDescImpl.ofValidated(baseType); 884 } 885 886 public static PrimitiveTypeInfo get(Class<?> cl) { 887 // Uses if chain for speed: 8284880 888 if (cl == int.class) return INT; 889 if (cl == long.class) return LONG; 890 if (cl == boolean.class) return BOOLEAN; 891 if (cl == short.class) return SHORT; 892 if (cl == byte.class) return BYTE; 893 if (cl == char.class) return CHAR; 894 if (cl == float.class) return FLOAT; 895 if (cl == double.class) return DOUBLE; 896 throw new AssertionError(cl); 897 } 898 899 public MethodRefEntry wrapperMethodRef(ConstantPoolBuilder cp) { 900 return cp.methodRefEntry(wrapperClass, "valueOf", wrapperMethodType); 901 } 902 903 public MethodRefEntry unwrapMethodRef(ConstantPoolBuilder cp) { 904 return cp.methodRefEntry(wrapperClass, unwrapMethodName, unwrapMethodType); 905 } 906 907 public FieldRefEntry typeFieldRef(ConstantPoolBuilder cp) { 908 return cp.fieldRefEntry(wrapperClass, "TYPE", CD_Class); 909 } 910 } 911 } --- EOF ---