/* * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * The {@code java.lang.invoke} package contains dynamic language support provided directly by * the Java core class libraries and virtual machine. * *

* Historic Note: In some early versions of Java SE 7, * the name of this package is {@code java.dyn}. *

* Certain types in this package have special relations to dynamic * language support in the virtual machine: *

* *

Corresponding JVM bytecode format changes

* The following low-level information is presented here as a preview of * changes being made to the Java Virtual Machine specification for JSR 292. * This information will be incorporated in a future version of the JVM specification. * *

{@code invokedynamic} instruction format

* In bytecode, an {@code invokedynamic} instruction is formatted as five bytes. * The first byte is the opcode 186 (hexadecimal {@code BA}). * The next two bytes are a constant pool index (in the same format as for the other {@code invoke} instructions). * The final two bytes are reserved for future use and required to be zero. * The constant pool reference of an {@code invokedynamic} instruction is to a entry * with tag {@code CONSTANT_InvokeDynamic} (decimal 18). See below for its format. * The entry specifies the following information: * *

* Each instance of an {@code invokedynamic} instruction is called a dynamic call site. * Multiple instances of an {@code invokedynamic} instruction can share a single * {@code CONSTANT_InvokeDynamic} entry. * In any case, distinct call sites always have distinct linkage state. *

* A dynamic call site is originally in an unlinked state. In this state, there is * no target method for the call site to invoke. * A dynamic call site is linked by means of a bootstrap method, * as described below. * *

* Historic Note: Some older JVMs may allow the index of a {@code CONSTANT_NameAndType} * instead of a {@code CONSTANT_InvokeDynamic}. In earlier, obsolete versions of this API, the * bootstrap method was specified dynamically, in a per-class basis, during class initialization. * *

constant pool entries for {@code invokedynamic} instructions

* If a constant pool entry has the tag {@code CONSTANT_InvokeDynamic} (decimal 18), * it must contain exactly four more bytes after the tag. * These bytes are interpreted as two 16-bit indexes, in the usual {@code u2} format. * The first pair of bytes after the tag must be an index into a side table called the * bootstrap method table, which is stored in the {@code BootstrapMethods} * attribute as described below. * The second pair of bytes must be an index to a {@code CONSTANT_NameAndType}. *

* The first index specifies a bootstrap method used by the associated dynamic call sites. * The second index specifies the method name, argument types, and return type of the dynamic call site. * The structure of such an entry is therefore analogous to a {@code CONSTANT_Methodref}, * except that the bootstrap method specifier reference replaces * the {@code CONSTANT_Class} reference of a {@code CONSTANT_Methodref} entry. * *

constant pool entries for {@linkplain java.dyn.MethodType method types}

* If a constant pool entry has the tag {@code CONSTANT_MethodType} (decimal 16), * it must contain exactly two more bytes, which must be an index to a {@code CONSTANT_Utf8} * entry which represents a method type descriptor. *

* The JVM will ensure that on first * execution of an {@code ldc} instruction for this entry, a {@link java.dyn.MethodType MethodType} * will be created which represents the type descriptor. * Any classes mentioned in the {@code MethodType} will be loaded if necessary, * but not initialized. * Access checking and error reporting is performed exactly as it is for * references by {@code ldc} instructions to {@code CONSTANT_Class} constants. * *

constant pool entries for {@linkplain java.dyn.MethodHandle method handles}

* If a constant pool entry has the tag {@code CONSTANT_MethodHandle} (decimal 15), * it must contain exactly three more bytes. The first byte after the tag is a subtag * value which must be in the range 1 through 9, and the last two must be an index to a * {@code CONSTANT_Fieldref}, {@code CONSTANT_Methodref}, or * {@code CONSTANT_InterfaceMethodref} entry which represents a field or method * for which a method handle is to be created. * Furthermore, the subtag value and the type of the constant index value * must agree according to the table below. *

* The JVM will ensure that on first execution of an {@code ldc} instruction * for this entry, a {@link java.dyn.MethodHandle MethodHandle} will be created which represents * the field or method reference, according to the specific mode implied by the subtag. *

* As with {@code CONSTANT_Class} and {@code CONSTANT_MethodType} constants, * the {@code Class} or {@code MethodType} object which reifies the field or method's * type is created. Any classes mentioned in this reification will be loaded if necessary, * but not initialized, and access checking and error reporting performed as usual. *

* The method handle itself will have a type and behavior determined by the subtag as follows: * * * * * * * * * * * * * * * * * * * * * *
Nsubtag namememberMH typebytecode behaviorlookup expression
1REF_getFieldC.f:T(C)Tgetfield C.f:T{@linkplain java.dyn.MethodHandles.Lookup#findGetter findGetter(C.class,"f",T.class)}
2REF_getStaticC.f:T( )Tgetstatic C.f:T{@linkplain java.dyn.MethodHandles.Lookup#findStaticGetter findStaticGetter(C.class,"f",T.class)}
3REF_putFieldC.f:T(C,T)voidputfield C.f:T{@linkplain java.dyn.MethodHandles.Lookup#findSetter findSetter(C.class,"f",T.class)}
4REF_putStaticC.f:T(T)voidputstatic C.f:T{@linkplain java.dyn.MethodHandles.Lookup#findStaticSetter findStaticSetter(C.class,"f",T.class)}
5REF_invokeVirtualC.m(A*)T(C,A*)Tinvokevirtual C.m(A*)T{@linkplain java.dyn.MethodHandles.Lookup#findVirtual findVirtual(C.class,"m",MT)}
6REF_invokeStaticC.m(A*)T(C,A*)Tinvokestatic C.m(A*)T{@linkplain java.dyn.MethodHandles.Lookup#findStatic findStatic(C.class,"m",MT)}
7REF_invokeSpecialC.m(A*)T(C,A*)Tinvokespecial C.m(A*)T{@linkplain java.dyn.MethodHandles.Lookup#findSpecial findSpecial(C.class,"m",MT,this.class)}
8REF_newInvokeSpecialC.<init>(A*)void(A*)Cnew C; dup; invokespecial C.<init>(A*)void{@linkplain java.dyn.MethodHandles.Lookup#findConstructor findConstructor(C.class,MT)}
9REF_invokeInterfaceC.m(A*)T(C,A*)Tinvokeinterface C.m(A*)T{@linkplain java.dyn.MethodHandles.Lookup#findVirtual findVirtual(C.class,"m",MT)}
*
* Here, the type {@code C} is taken from the {@code CONSTANT_Class} reference associated * with the {@code CONSTANT_NameAndType} descriptor. * The field name {@code f} or method name {@code m} is taken from the {@code CONSTANT_NameAndType} * as is the result type {@code T} and (in the case of a method or constructor) the argument type sequence * {@code A*}. *

* Each method handle constant has an equivalent instruction sequence called its bytecode behavior. * In general, creating a method handle constant can be done in exactly the same circumstances that * the JVM would successfully resolve the symbolic references in the bytecode behavior. * Also, the type of a method handle constant is such that a valid {@code invokeExact} call * on the method handle has exactly the same JVM stack effects as the bytecode behavior. * Finally, calling a method handle constant on a valid set of arguments has exactly the same effect * and returns the same result (if any) as the corresponding bytecode behavior. *

* Each method handle constant also has an equivalent reflective lookup expression, * which is a query to a method in {@link java.dyn.MethodHandles.Lookup}. * In the example lookup method expression given in the table above, the name {@code MT} * stands for a {@code MethodType} built from {@code T} and the sequence of argument types {@code A*}. * (Note that the type {@code C} is not prepended to the query type {@code MT} even if the member is non-static.) * In the case of {@code findSpecial}, the name {@code this.class} refers to the class containing * the bytecodes. *

* The special name {@code } is not allowed. * The special name {@code } is not allowed except for subtag 8 as shown. *

* The JVM verifier and linker apply the same access checks and restrictions for these references as for the hypothetical * bytecode instructions specified in the last column of the table. * A method handle constant will successfully resolve to a method handle if the symbolic references * of the corresponding bytecode instruction(s) would also resolve successfully. * Otherwise, an attempt to resolve the constant will throw equivalent linkage errors. * In particular, method handles to * private and protected members can be created in exactly those classes for which the corresponding * normal accesses are legal. *

* A constant may refer to a method or constructor with the {@code varargs} * bit (hexadecimal {@code 0x0080}) set in its modifier bitmask. * The method handle constant produced for such a method behaves as if * it were created by {@link java.dyn.MethodHandle#asVarargsCollector asVarargsCollector}. * In other words, the constant method handle will exhibit variable arity, * when invoked via {@code invokeGeneric}. * On the other hand, its behavior with respect to {@code invokeExact} will be the same * as if the {@code varargs} bit were not set. *

* Although the {@code CONSTANT_MethodHandle} and {@code CONSTANT_MethodType} constant types * resolve class names, they do not force class initialization. * Method handle constants for subtags {@code REF_getStatic}, {@code REF_putStatic}, and {@code REF_invokeStatic} * may force class initialization on their first invocation, just like the corresponding bytecodes. *

* The rules of section 5.4.3 of the * JVM Specification * apply to the resolution of {@code CONSTANT_MethodType}, {@code CONSTANT_MethodHandle}, * and {@code CONSTANT_InvokeDynamic} constants, * by the execution of {@code invokedynamic} and {@code ldc} instructions. * (Roughly speaking, this means that every use of a constant pool entry * must lead to the same outcome. * If the resolution succeeds, the same object reference is produced * by every subsequent execution of the same instruction. * If the resolution of the constant causes an error to occur, * the same error will be re-thrown on every subsequent attempt * to use this particular constant.) *

* Constants created by the resolution of these constant pool types are not necessarily * interned. Except for {@code CONSTANT_Class} and {@code CONSTANT_String} entries, * two distinct constant pool entries might not resolve to the same reference * even if they contain the same symbolic reference. * *

Bootstrap Methods

* Before the JVM can execute a dynamic call site (an {@code invokedynamic} instruction), * the call site must first be linked. * Linking is accomplished by calling a bootstrap method * which is given the static information content of the call site, * and which must produce a {@link java.dyn.MethodHandle method handle} * that gives the behavior of the call site. *

* Each {@code invokedynamic} instruction statically specifies its own * bootstrap method as a constant pool reference. * The constant pool reference also specifies the call site's name and type descriptor, * just like {@code invokevirtual} and the other invoke instructions. *

* Linking starts with resolving the constant pool entry for the * bootstrap method, and resolving a {@link java.dyn.MethodType MethodType} object for * the type descriptor of the dynamic call site. * This resolution process may trigger class loading. * It may therefore throw an error if a class fails to load. * This error becomes the abnormal termination of the dynamic * call site execution. * Linkage does not trigger class initialization. *

* Next, the bootstrap method call is started, with at least four values being stacked: *

* The method handle is then applied to the other values as if by * {@link java.dyn.MethodHandle#invokeGeneric invokeGeneric}. * The returned result must be a {@link java.dyn.CallSite CallSite} (or a subclass). * The type of the call site's target must be exactly equal to the type * derived from the dynamic call site's type descriptor and passed to * the bootstrap method. * The call site then becomes permanently linked to the dynamic call site. *

* As long as each bootstrap method can be correctly invoked * by invokeGeneric, its detailed type is arbitrary. * For example, the first argument could be {@code Object} * instead of {@code MethodHandles.Lookup}, and the return type * could also be {@code Object} instead of {@code CallSite}. *

* As with any method handle constant, a {@code varargs} modifier bit * on the bootstrap method is ignored. *

* Note that the first argument of the bootstrap method cannot be * a simple {@code Class} reference. (This is a change from earlier * versions of this specification. If the caller class is needed, * it is easy to {@linkplain java.dyn.MethodHandles.Lookup#lookupClass() extract it} * from the {@code Lookup} object.) *

* After resolution, the linkage process may fail in a variety of ways. * All failures are reported by an {@link java.dyn.InvokeDynamicBootstrapError InvokeDynamicBootstrapError}, * which is thrown as the abnormal termination of the dynamic call * site execution. * The following circumstances will cause this: *

* *

timing of linkage

* A dynamic call site is linked just before its first execution. * The bootstrap method call implementing the linkage occurs within * a thread that is attempting a first execution. *

* If there are several such threads, the bootstrap method may be * invoked in several threads concurrently. * Therefore, bootstrap methods which access global application * data must take the usual precautions against race conditions. * In any case, every {@code invokedynamic} instruction is either * unlinked or linked to a unique {@code CallSite} object. *

* In an application which requires dynamic call sites with individually * mutable behaviors, their bootstrap methods should produce distinct * {@link java.dyn.CallSite CallSite} objects, one for each linkage request. * Alternatively, an application can link a single {@code CallSite} object * to several {@code invokedynamic} instructions, in which case * a change to the target method will become visible at each of * the instructions. *

* If several threads simultaneously execute a bootstrap method for a single dynamic * call site, the JVM must choose one {@code CallSite} object and install it visibly to * all threads. Any other bootstrap method calls are allowed to complete, but their * results are ignored, and their dynamic call site invocations proceed with the originally * chosen target object. * *

* Historic Note: Unlike some previous versions of this specification, * these rules do not enable the JVM to duplicate dynamic call sites, * or to issue “causeless” bootstrap method calls. * Every dynamic call site transitions at most once from unlinked to linked, * just before its first invocation. * *

the {@code BootstrapMethods} attribute

* Each {@code CONSTANT_InvokeDynamic} entry contains an index which references * a bootstrap method specifier; all such specifiers are contained in a separate array. * This array is defined by a class attribute named {@code BootstrapMethods}. * The body of this attribute consists of a sequence of byte pairs, all interpreted as * as 16-bit counts or constant pool indexes, in the {@code u2} format. * The attribute body starts with a count of bootstrap method specifiers, * which is immediately followed by the sequence of specifiers. *

* Each bootstrap method specifier contains an index to a * {@code CONSTANT_MethodHandle} constant, which is the bootstrap * method itself. * This is followed by a count, and then a sequence (perhaps empty) of * indexes to additional static arguments * for the bootstrap method. *

* During class loading, the verifier must check the structure of the * {@code BootstrapMethods} attribute. In particular, each constant * pool index must be of the correct type. A bootstrap method index * must refer to a {@code CONSTANT_MethodHandle} (tag 15). * Every other index must refer to a valid operand of an * {@code ldc_w} or {@code ldc2_w} instruction (tag 3..8 or 15..16). * *

static arguments to the bootstrap method

* An {@code invokedynamic} instruction specifies at least three arguments * to pass to its bootstrap method: * The caller class (expressed as a {@link java.dyn.MethodHandles.Lookup Lookup object}, * the name (extracted from the {@code CONSTANT_NameAndType} entry), * and the type (also extracted from the {@code CONSTANT_NameAndType} entry). * The {@code invokedynamic} instruction may specify additional metadata values * to pass to its bootstrap method. * Collectively, these values are called static arguments to the * {@code invokedynamic} instruction, because they are used once at link * time to determine the instruction's behavior on subsequent sets of * dynamic arguments. *

* Static arguments are used to communicate application-specific meta-data * to the bootstrap method. * Drawn from the constant pool, they may include references to classes, method handles, * strings, or numeric data that may be relevant to the task of linking that particular call site. *

* Static arguments are specified constant pool indexes stored in the {@code BootstrapMethods} attribute. * Before the bootstrap method is invoked, each index is used to compute an {@code Object} * reference to the indexed value in the constant pool. * The valid constant pool entries are listed in this table: * * * * * * * * * * * *
entry typeargument typeargument value
CONSTANT_Stringjava.lang.Stringthe indexed string literal
CONSTANT_Classjava.lang.Classthe indexed class, resolved
CONSTANT_Integerjava.lang.Integerthe indexed int value
CONSTANT_Longjava.lang.Longthe indexed long value
CONSTANT_Floatjava.lang.Floatthe indexed float value
CONSTANT_Doublejava.lang.Doublethe indexed double value
CONSTANT_MethodHandlejava.dyn.MethodHandlethe indexed method handle constant
CONSTANT_MethodTypejava.dyn.MethodTypethe indexed method type constant
*
*

* If a given {@code invokedynamic} instruction specifies no static arguments, * the instruction's bootstrap method will be invoked on three arguments, * conveying the instruction's caller class, name, and method type. * If the {@code invokedynamic} instruction specifies one or more static arguments, * those values will be passed as additional arguments to the method handle. * (Note that because there is a limit of 255 arguments to any method, * at most 252 extra arguments can be supplied.) * The bootstrap method will be invoked as if by either {@code invokeGeneric} * or {@code invokeWithArguments}. (There is no way to tell the difference.) *

* The normal argument conversion rules for {@code invokeGeneric} apply to all stacked arguments. * For example, if a pushed value is a primitive type, it may be converted to a reference by boxing conversion. * If the bootstrap method is a variable arity method (its modifier bit {@code 0x0080} is set), * then some or all of the arguments specified here may be collected into a trailing array parameter. * (This is not a special rule, but rather a useful consequence of the interaction * between {@code CONSTANT_MethodHandle} constants, the modifier bit for variable arity methods, * and the {@code java.dyn.MethodHandle#asVarargsCollector asVarargsCollector} transformation.) *

* Given these rules, here are examples of legal bootstrap method declarations, * given various numbers {@code N} of extra arguments. * The first rows (marked {@code *}) will work for any number of extra arguments. * * * * * * * * * * * * *
Nsample bootstrap method
*CallSite bootstrap(Lookup caller, String name, MethodType type, Object... args)
*CallSite bootstrap(Object... args)
*CallSite bootstrap(Object caller, Object... nameAndTypeWithArgs)
0CallSite bootstrap(Lookup caller, String name, MethodType type)
0CallSite bootstrap(Lookup caller, Object... nameAndType)
1CallSite bootstrap(Lookup caller, String name, MethodType type, Object arg)
2CallSite bootstrap(Lookup caller, String name, MethodType type, Object... args)
2CallSite bootstrap(Lookup caller, String name, MethodType type, String... args)
2CallSite bootstrap(Lookup caller, String name, MethodType type, String x, int y)
*
* The last example assumes that the extra arguments are of type * {@code CONSTANT_String} and {@code CONSTANT_Integer}, respectively. * The second-to-last example assumes that all extra arguments are of type * {@code CONSTANT_String}. * The other examples work with all types of extra arguments. *

* As noted above, the actual method type of the bootstrap method can vary. * For example, the fourth argument could be {@code MethodHandle}, * if that is the type of the corresponding constant in * the {@code CONSTANT_InvokeDynamic} entry. * In that case, the {@code invokeGeneric} call will pass the extra method handle * constant as an {@code Object}, but the type matching machinery of {@code invokeGeneric} * will cast the reference back to {@code MethodHandle} before invoking the bootstrap method. * (If a string constant were passed instead, by badly generated code, that cast would then fail, * resulting in an {@code InvokeDynamicBootstrapError}.) *

* Extra bootstrap method arguments are intended to allow language implementors * to safely and compactly encode metadata. * In principle, the name and extra arguments are redundant, * since each call site could be given its own unique bootstrap method. * Such a practice is likely to produce large class files and constant pools. * *

Structure Summary

*
// summary of constant and attribute structures
struct CONSTANT_MethodHandle_info {
  u1 tag = 15;
  u1 reference_kind;       // 1..8 (one of REF_invokeVirtual, etc.)
  u2 reference_index;      // index to CONSTANT_Fieldref or *Methodref
}
struct CONSTANT_MethodType_info {
  u1 tag = 16;
  u2 descriptor_index;    // index to CONSTANT_Utf8, as in NameAndType
}
struct CONSTANT_InvokeDynamic_info {
  u1 tag = 18;
  u2 bootstrap_method_attr_index;  // index into BootstrapMethods_attr
  u2 name_and_type_index;          // index to CONSTANT_NameAndType, as in Methodref
}
struct BootstrapMethods_attr {
 u2 name;  // CONSTANT_Utf8 = "BootstrapMethods"
 u4 size;
 u2 bootstrap_method_count;
 struct bootstrap_method_specifier {
   u2 bootstrap_method_ref;  // index to CONSTANT_MethodHandle
   u2 bootstrap_argument_count;
   u2 bootstrap_arguments[bootstrap_argument_count];  // constant pool indexes
 } bootstrap_methods[bootstrap_method_count];
}
 * 
* * @author John Rose, JSR 292 EG */ package java.dyn;