< prev index next >

src/java.base/share/classes/java/lang/invoke/BoundMethodHandle.java

Print this page




  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.invoke;
  27 
  28 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  29 import static java.lang.invoke.LambdaForm.*;
  30 import static java.lang.invoke.LambdaForm.BasicType.*;
  31 import static java.lang.invoke.MethodHandleStatics.*;
  32 
  33 import java.lang.invoke.LambdaForm.NamedFunction;
  34 import java.lang.invoke.MethodHandles.Lookup;
  35 import java.lang.reflect.Field;
  36 import java.util.Arrays;
  37 import java.util.HashMap;


  38 
  39 import sun.invoke.util.ValueConversions;
  40 import sun.invoke.util.Wrapper;
  41 
  42 import jdk.internal.org.objectweb.asm.ClassWriter;
  43 import jdk.internal.org.objectweb.asm.MethodVisitor;
  44 import jdk.internal.org.objectweb.asm.Type;
  45 
  46 /**
  47  * The flavor of method handle which emulates an invoke instruction
  48  * on a predetermined argument.  The JVM dispatches to the correct method
  49  * when the handle is created, not when it is invoked.
  50  *
  51  * All bound arguments are encapsulated in dedicated species.
  52  */
  53 /*non-public*/ abstract class BoundMethodHandle extends MethodHandle {
  54 
  55     /*non-public*/ BoundMethodHandle(MethodType type, LambdaForm form) {
  56         super(type, form);
  57         assert(speciesData() == speciesData(form));


 338         private SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) {
 339             this.typeChars = types;
 340             this.typeCodes = basicTypes(types);
 341             this.clazz = clazz;
 342             if (!INIT_DONE) {
 343                 this.constructor = new MethodHandle[1];  // only one ctor
 344                 this.getters = new MethodHandle[types.length()];
 345                 this.nominalGetters = new NamedFunction[types.length()];
 346             } else {
 347                 this.constructor = Factory.makeCtors(clazz, types, null);
 348                 this.getters = Factory.makeGetters(clazz, types, null);
 349                 this.nominalGetters = Factory.makeNominalGetters(types, null, this.getters);
 350             }
 351             this.extensions = new SpeciesData[ARG_TYPE_LIMIT];
 352         }
 353 
 354         private void initForBootstrap() {
 355             assert(!INIT_DONE);
 356             if (constructor() == null) {
 357                 String types = typeChars;

 358                 Factory.makeCtors(clazz, types, this.constructor);
 359                 Factory.makeGetters(clazz, types, this.getters);
 360                 Factory.makeNominalGetters(types, this.nominalGetters, this.getters);
 361             }
 362         }
 363 
 364         private SpeciesData(String typeChars) {
 365             // Placeholder only.
 366             this.typeChars = typeChars;
 367             this.typeCodes = basicTypes(typeChars);
 368             this.clazz = null;
 369             this.constructor = null;
 370             this.getters = null;
 371             this.nominalGetters = null;
 372             this.extensions = null;
 373         }
 374         private boolean isPlaceholder() { return clazz == null; }
 375 
 376         private static final HashMap<String, SpeciesData> CACHE = new HashMap<>();
 377         static { CACHE.put("", EMPTY); }  // make bootstrap predictable
 378         private static final boolean INIT_DONE;  // set after <clinit> finishes...
 379 
 380         SpeciesData extendWith(byte type) {
 381             return extendWith(BasicType.basicType(type));
 382         }
 383 
 384         SpeciesData extendWith(BasicType type) {
 385             int ord = type.ordinal();
 386             SpeciesData d = extensions[ord];
 387             if (d != null)  return d;
 388             extensions[ord] = d = get(typeChars+type.basicTypeChar());
 389             return d;
 390         }
 391 
 392         private static SpeciesData get(String types) {
 393             // Acquire cache lock for query.
 394             SpeciesData d = lookupCache(types);
 395             if (!d.isPlaceholder())
 396                 return d;
 397             synchronized (d) {
 398                 // Use synch. on the placeholder to prevent multiple instantiation of one species.
 399                 // Creating this class forces a recursive call to getForClass.
 400                 if (lookupCache(types).isPlaceholder())
 401                     Factory.generateConcreteBMHClass(types);
 402             }
 403             // Reacquire cache lock.
 404             d = lookupCache(types);
 405             // Class loading must have upgraded the cache.
 406             assert(d != null && !d.isPlaceholder());
 407             return d;
 408         }


 409         static SpeciesData getForClass(String types, Class<? extends BoundMethodHandle> clazz) {
 410             // clazz is a new class which is initializing its SPECIES_DATA field
 411             return updateCache(types, new SpeciesData(types, clazz));
 412         }
 413         private static synchronized SpeciesData lookupCache(String types) {
 414             SpeciesData d = CACHE.get(types);
 415             if (d != null)  return d;
 416             d = new SpeciesData(types);
 417             assert(d.isPlaceholder());
 418             CACHE.put(types, d);
 419             return d;
 420         }
 421         private static synchronized SpeciesData updateCache(String types, SpeciesData d) {
 422             SpeciesData d2;
 423             assert((d2 = CACHE.get(types)) == null || d2.isPlaceholder());
 424             assert(!d.isPlaceholder());
 425             CACHE.put(types, d);
 426             return d;
 427         }
 428 
 429         static {
 430             // pre-fill the BMH speciesdata cache with BMH's inner classes
 431             final Class<BoundMethodHandle> rootCls = BoundMethodHandle.class;




 432             try {
 433                 for (Class<?> c : rootCls.getDeclaredClasses()) {
 434                     if (rootCls.isAssignableFrom(c)) {
 435                         final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class);
 436                         SpeciesData d = Factory.speciesDataFromConcreteBMHClass(cbmh);
 437                         assert(d != null) : cbmh.getName();
 438                         assert(d.clazz == cbmh);
 439                         assert(d == lookupCache(d.typeChars));
 440                     }
 441                 }
 442             } catch (Throwable e) {
 443                 throw newInternalError(e);
 444             }
 445 
 446             for (SpeciesData d : CACHE.values()) {
 447                 d.initForBootstrap();
 448             }







 449             // Note:  Do not simplify this, because INIT_DONE must not be
 450             // a compile-time constant during bootstrapping.
 451             INIT_DONE = Boolean.TRUE;
 452         }
 453     }
 454 
 455     static SpeciesData getSpeciesData(String types) {
 456         return SpeciesData.get(types);
 457     }
 458 
 459     /**
 460      * Generation of concrete BMH classes.
 461      *
 462      * A concrete BMH species is fit for binding a number of values adhering to a
 463      * given type pattern. Reference types are erased.
 464      *
 465      * BMH species are cached by type pattern.
 466      *
 467      * A BMH species has a number of fields with the concrete (possibly erased) types of
 468      * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs,


 476         static final String MH       = "java/lang/invoke/MethodHandle";
 477         static final String MH_SIG   = "L"+MH+";";
 478         static final String BMH      = "java/lang/invoke/BoundMethodHandle";
 479         static final String BMH_SIG  = "L"+BMH+";";
 480         static final String SPECIES_DATA     = "java/lang/invoke/BoundMethodHandle$SpeciesData";
 481         static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";";
 482 
 483         static final String SPECIES_PREFIX_NAME = "Species_";
 484         static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME;
 485 
 486         static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG;
 487         static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG;
 488         static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG;
 489         static final String VOID_SIG   = "()V";
 490         static final String INT_SIG    = "()I";
 491 
 492         static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;";
 493 
 494         static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
 495 




















 496         /**
 497          * Generate a concrete subclass of BMH for a given combination of bound types.
 498          *
 499          * A concrete BMH species adheres to the following schema:
 500          *
 501          * <pre>
 502          * class Species_[[types]] extends BoundMethodHandle {
 503          *     [[fields]]
 504          *     final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); }
 505          * }
 506          * </pre>
 507          *
 508          * The {@code [[types]]} signature is precisely the string that is passed to this
 509          * method.
 510          *
 511          * The {@code [[fields]]} section consists of one field definition per character in
 512          * the type signature, adhering to the naming schema described in the definition of
 513          * {@link #makeFieldName}.
 514          *
 515          * For example, a concrete BMH species for two reference and one integral bound values


 698             mv = cw.visitMethod(NOT_ACC_PUBLIC | ACC_STATIC, "<clinit>", VOID_SIG, null, null);
 699             mv.visitCode();
 700             mv.visitLdcInsn(types);
 701             mv.visitLdcInsn(Type.getObjectType(className));
 702             mv.visitMethodInsn(INVOKESTATIC, SPECIES_DATA, "getForClass", BMHSPECIES_DATA_GFC_SIG, false);
 703             mv.visitFieldInsn(PUTSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 704             mv.visitInsn(RETURN);
 705             mv.visitMaxs(0, 0);
 706             mv.visitEnd();
 707 
 708             cw.visitEnd();
 709 
 710             // load class
 711             final byte[] classFile = cw.toByteArray();
 712             InvokerBytecodeGenerator.maybeDump(className, classFile);
 713             Class<? extends BoundMethodHandle> bmhClass =
 714                 //UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class);
 715                 UNSAFE.defineClass(className, classFile, 0, classFile.length,
 716                                    BoundMethodHandle.class.getClassLoader(), null)
 717                     .asSubclass(BoundMethodHandle.class);
 718             UNSAFE.ensureClassInitialized(bmhClass);
 719 
 720             return bmhClass;
 721         }
 722 
 723         private static int typeLoadOp(char t) {
 724             switch (t) {
 725             case 'L': return ALOAD;
 726             case 'I': return ILOAD;
 727             case 'J': return LLOAD;
 728             case 'F': return FLOAD;
 729             case 'D': return DLOAD;
 730             default : throw newInternalError("unrecognized type " + t);
 731             }
 732         }
 733 
 734         private static void emitPushFields(String types, String className, MethodVisitor mv) {
 735             for (int i = 0; i < types.length(); ++i) {
 736                 char tc = types.charAt(i);
 737                 mv.visitVarInsn(ALOAD, 0);
 738                 mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc));




  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.invoke;
  27 
  28 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  29 import static java.lang.invoke.LambdaForm.*;
  30 import static java.lang.invoke.LambdaForm.BasicType.*;
  31 import static java.lang.invoke.MethodHandleStatics.*;
  32 
  33 import java.lang.invoke.LambdaForm.NamedFunction;
  34 import java.lang.invoke.MethodHandles.Lookup;
  35 import java.lang.reflect.Field;
  36 import java.util.Arrays;
  37 import java.util.function.Function;
  38 import java.util.concurrent.ConcurrentMap;
  39 import java.util.concurrent.ConcurrentHashMap;
  40 
  41 import sun.invoke.util.ValueConversions;
  42 import sun.invoke.util.Wrapper;
  43 
  44 import jdk.internal.org.objectweb.asm.ClassWriter;
  45 import jdk.internal.org.objectweb.asm.MethodVisitor;
  46 import jdk.internal.org.objectweb.asm.Type;
  47 
  48 /**
  49  * The flavor of method handle which emulates an invoke instruction
  50  * on a predetermined argument.  The JVM dispatches to the correct method
  51  * when the handle is created, not when it is invoked.
  52  *
  53  * All bound arguments are encapsulated in dedicated species.
  54  */
  55 /*non-public*/ abstract class BoundMethodHandle extends MethodHandle {
  56 
  57     /*non-public*/ BoundMethodHandle(MethodType type, LambdaForm form) {
  58         super(type, form);
  59         assert(speciesData() == speciesData(form));


 340         private SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) {
 341             this.typeChars = types;
 342             this.typeCodes = basicTypes(types);
 343             this.clazz = clazz;
 344             if (!INIT_DONE) {
 345                 this.constructor = new MethodHandle[1];  // only one ctor
 346                 this.getters = new MethodHandle[types.length()];
 347                 this.nominalGetters = new NamedFunction[types.length()];
 348             } else {
 349                 this.constructor = Factory.makeCtors(clazz, types, null);
 350                 this.getters = Factory.makeGetters(clazz, types, null);
 351                 this.nominalGetters = Factory.makeNominalGetters(types, null, this.getters);
 352             }
 353             this.extensions = new SpeciesData[ARG_TYPE_LIMIT];
 354         }
 355 
 356         private void initForBootstrap() {
 357             assert(!INIT_DONE);
 358             if (constructor() == null) {
 359                 String types = typeChars;
 360                 CACHE.put(types, this);
 361                 Factory.makeCtors(clazz, types, this.constructor);
 362                 Factory.makeGetters(clazz, types, this.getters);
 363                 Factory.makeNominalGetters(types, this.nominalGetters, this.getters);
 364             }
 365         }
 366 
 367         private static final ConcurrentMap<String, SpeciesData> CACHE = new ConcurrentHashMap<>();













 368         private static final boolean INIT_DONE;  // set after <clinit> finishes...
 369 
 370         SpeciesData extendWith(byte type) {
 371             return extendWith(BasicType.basicType(type));
 372         }
 373 
 374         SpeciesData extendWith(BasicType type) {
 375             int ord = type.ordinal();
 376             SpeciesData d = extensions[ord];
 377             if (d != null)  return d;
 378             extensions[ord] = d = get(typeChars+type.basicTypeChar());
 379             return d;
 380         }
 381 
 382         private static SpeciesData get(String types) {
 383             SpeciesData d = CACHE.get(types);
 384             if (d == null) {
 385                 Class<? extends BoundMethodHandle> bmhcl = Factory.getConcreteBMHClass(types);
 386                 // obtain value of SPECIES_DATA static field.
 387                 // This triggers class initialization which might fail!
 388                 d = Factory.speciesDataFromConcreteBMHClass(bmhcl);
 389                 SpeciesData d2 = CACHE.putIfAbsent(types, d);
 390                 assert d2 == null || d2 == d;
 391             }





 392             return d;
 393         }
 394 
 395         // a call-back from generated BMH subclass' <clinit>
 396         static SpeciesData getForClass(String types, Class<? extends BoundMethodHandle> clazz) {
 397             // clazz is a new class which is initializing its SPECIES_DATA field
 398             return new SpeciesData(types, clazz);















 399         }
 400 
 401         /**
 402          * This is to be called when assertions are enabled. It checks whether SpeciesData for all of the statically
 403          * defined species subclasses of BoundMethodHandle has been added to the SpeciesData cache. See below in the
 404          * static initializer for
 405          */
 406         static boolean speciesDataCachePopulated() {
 407             Class<BoundMethodHandle> rootCls = BoundMethodHandle.class;
 408             try {
 409                 for (Class<?> c : rootCls.getDeclaredClasses()) {
 410                     if (rootCls.isAssignableFrom(c)) {
 411                         final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class);
 412                         SpeciesData d = Factory.speciesDataFromConcreteBMHClass(cbmh);
 413                         assert(d != null) : cbmh.getName();
 414                         assert(d.clazz == cbmh);
 415                         assert(CACHE.get(d.typeChars) == d);
 416                     }
 417                 }
 418             } catch (Throwable e) {
 419                 throw newInternalError(e);
 420             }
 421             return true;


 422         }
 423 
 424         static {
 425             // Pre-fill the BMH species-data cache with EMPTY and all BMH's inner subclasses.
 426             EMPTY.initForBootstrap();
 427             Species_L.SPECIES_DATA.initForBootstrap();
 428             // check that all static SpeciesData instances have been initialized
 429             assert speciesDataCachePopulated();
 430             // Note:  Do not simplify this, because INIT_DONE must not be
 431             // a compile-time constant during bootstrapping.
 432             INIT_DONE = Boolean.TRUE;
 433         }
 434     }
 435 
 436     static SpeciesData getSpeciesData(String types) {
 437         return SpeciesData.get(types);
 438     }
 439 
 440     /**
 441      * Generation of concrete BMH classes.
 442      *
 443      * A concrete BMH species is fit for binding a number of values adhering to a
 444      * given type pattern. Reference types are erased.
 445      *
 446      * BMH species are cached by type pattern.
 447      *
 448      * A BMH species has a number of fields with the concrete (possibly erased) types of
 449      * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs,


 457         static final String MH       = "java/lang/invoke/MethodHandle";
 458         static final String MH_SIG   = "L"+MH+";";
 459         static final String BMH      = "java/lang/invoke/BoundMethodHandle";
 460         static final String BMH_SIG  = "L"+BMH+";";
 461         static final String SPECIES_DATA     = "java/lang/invoke/BoundMethodHandle$SpeciesData";
 462         static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";";
 463 
 464         static final String SPECIES_PREFIX_NAME = "Species_";
 465         static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME;
 466 
 467         static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG;
 468         static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG;
 469         static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG;
 470         static final String VOID_SIG   = "()V";
 471         static final String INT_SIG    = "()I";
 472 
 473         static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;";
 474 
 475         static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
 476 
 477         static final ConcurrentMap<String, Class<? extends BoundMethodHandle>> CLASS_CACHE = new ConcurrentHashMap<>();
 478 
 479         /**
 480          * Get a concrete subclass of BMH for a given combination of bound types.
 481          *
 482          * @param types the type signature, wherein reference types are erased to 'L'
 483          * @return the concrete BMH class
 484          */
 485         static Class<? extends BoundMethodHandle> getConcreteBMHClass(String types) {
 486             // CHM.computeIfAbsent ensures generateConcreteBMHClass is called
 487             // only once per key.
 488             return CLASS_CACHE.computeIfAbsent(
 489                 types, new Function<String, Class<? extends BoundMethodHandle>>() {
 490                     @Override
 491                     public Class<? extends BoundMethodHandle> apply(String types) {
 492                         return generateConcreteBMHClass(types);
 493                     }
 494                 });
 495         }
 496 
 497         /**
 498          * Generate a concrete subclass of BMH for a given combination of bound types.
 499          *
 500          * A concrete BMH species adheres to the following schema:
 501          *
 502          * <pre>
 503          * class Species_[[types]] extends BoundMethodHandle {
 504          *     [[fields]]
 505          *     final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); }
 506          * }
 507          * </pre>
 508          *
 509          * The {@code [[types]]} signature is precisely the string that is passed to this
 510          * method.
 511          *
 512          * The {@code [[fields]]} section consists of one field definition per character in
 513          * the type signature, adhering to the naming schema described in the definition of
 514          * {@link #makeFieldName}.
 515          *
 516          * For example, a concrete BMH species for two reference and one integral bound values


 699             mv = cw.visitMethod(NOT_ACC_PUBLIC | ACC_STATIC, "<clinit>", VOID_SIG, null, null);
 700             mv.visitCode();
 701             mv.visitLdcInsn(types);
 702             mv.visitLdcInsn(Type.getObjectType(className));
 703             mv.visitMethodInsn(INVOKESTATIC, SPECIES_DATA, "getForClass", BMHSPECIES_DATA_GFC_SIG, false);
 704             mv.visitFieldInsn(PUTSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 705             mv.visitInsn(RETURN);
 706             mv.visitMaxs(0, 0);
 707             mv.visitEnd();
 708 
 709             cw.visitEnd();
 710 
 711             // load class
 712             final byte[] classFile = cw.toByteArray();
 713             InvokerBytecodeGenerator.maybeDump(className, classFile);
 714             Class<? extends BoundMethodHandle> bmhClass =
 715                 //UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class);
 716                 UNSAFE.defineClass(className, classFile, 0, classFile.length,
 717                                    BoundMethodHandle.class.getClassLoader(), null)
 718                     .asSubclass(BoundMethodHandle.class);

 719 
 720             return bmhClass;
 721         }
 722 
 723         private static int typeLoadOp(char t) {
 724             switch (t) {
 725             case 'L': return ALOAD;
 726             case 'I': return ILOAD;
 727             case 'J': return LLOAD;
 728             case 'F': return FLOAD;
 729             case 'D': return DLOAD;
 730             default : throw newInternalError("unrecognized type " + t);
 731             }
 732         }
 733 
 734         private static void emitPushFields(String types, String className, MethodVisitor mv) {
 735             for (int i = 0; i < types.length(); ++i) {
 736                 char tc = types.charAt(i);
 737                 mv.visitVarInsn(ALOAD, 0);
 738                 mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc));


< prev index next >