2 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
26 package java.lang.invoke;
28 import static java.lang.invoke.MethodHandleNatives.Constants.*;
29 import static java.lang.invoke.MethodHandleStatics.*;
30 import java.lang.invoke.MethodHandles.Lookup;
31 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
32 import java.lang.reflect.Constructor;
33 import java.lang.reflect.Field;
34 import java.lang.reflect.Member;
35 import java.lang.reflect.Method;
38 * The JVM interface for the method handles package is all here.
39 * This is an interface internal and private to an implementation of JSR 292.
40 * <em>This class is not part of the JSR 292 standard.</em>
43 class MethodHandleNatives {
45 private MethodHandleNatives() { } // static only
47 /// MemberName support
49 static void init(MemberName self, Object ref) {
50 self.clazz = ((Member)ref).getDeclaringClass();
53 static void expand(MemberName self) {
56 static MemberName resolve(MemberName self, Class<?> caller) throws LinkageError {
59 static int getMembers(Class<?> defc, String matchName, String matchSig,
60 int matchFlags, Class<?> caller, int skip, MemberName[] results) {
62 for (Method m : defc.getMethods()) {
63 if (skip == results.length) {
66 MemberName mn = new MemberName(m);
69 for (Constructor m : defc.getConstructors()) {
70 if (skip == results.length) {
73 MemberName mn = new MemberName(m);
76 for (Field m : defc.getFields()) {
77 if (skip == results.length) {
80 MemberName mn = new MemberName(m);
86 /// Field layout queries parallel to sun.misc.Unsafe:
87 static native long objectFieldOffset(MemberName self); // e.g., returns vmindex
88 static native long staticFieldOffset(MemberName self); // e.g., returns vmindex
89 static native Object staticFieldBase(MemberName self); // e.g., returns clazz
90 static native Object getMemberVMInfo(MemberName self); // returns {vmindex,vmtarget}
92 /// MethodHandle support
96 /** Tell the JVM that we need to change the target of a CallSite. */
97 static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
98 static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
101 // The JVM calls MethodHandleNatives.<clinit>. Cascade the <clinit> calls as needed:
102 MethodHandleImpl.initStatics();
105 // All compile-time constants go here.
106 // There is an opportunity to check them against the JVM's idea of them.
107 static class Constants {
108 Constants() { } // static only
110 static final int // for getConstant
112 GC_LAMBDA_SUPPORT = 5;
115 // The JVM uses values of -2 and above for vtable indexes.
116 // Field values are simple positive offsets.
117 // Ref: src/share/vm/oops/methodOop.hpp
118 // This value is negative enough to avoid such numbers,
119 // but not too negative.
121 MN_IS_METHOD = 0x00010000, // method (not constructor)
122 MN_IS_CONSTRUCTOR = 0x00020000, // constructor
123 MN_IS_FIELD = 0x00040000, // field
124 MN_IS_TYPE = 0x00080000, // nested type
125 MN_CALLER_SENSITIVE = 0x00100000, // @CallerSensitive annotation detected
126 MN_REFERENCE_KIND_SHIFT = 24, // refKind
127 MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
128 // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
129 MN_SEARCH_SUPERCLASSES = 0x00100000,
130 MN_SEARCH_INTERFACES = 0x00200000;
133 * Basic types as encoded in the JVM. These code values are not
134 * intended for use outside this class. They are used as part of
135 * a private interface between the JVM and this class.
153 * Constant pool entry types.
157 CONSTANT_Integer = 3,
163 CONSTANT_Fieldref = 9,
164 CONSTANT_Methodref = 10,
165 CONSTANT_InterfaceMethodref = 11,
166 CONSTANT_NameAndType = 12,
167 CONSTANT_MethodHandle = 15, // JSR 292
168 CONSTANT_MethodType = 16, // JSR 292
169 CONSTANT_InvokeDynamic = 18,
170 CONSTANT_LIMIT = 19; // Limit to tags found in classfiles
173 * Access modifier flags.
177 ACC_PRIVATE = 0x0002,
178 ACC_PROTECTED = 0x0004,
181 ACC_SYNCHRONIZED = 0x0020,
182 ACC_VOLATILE = 0x0040,
183 ACC_TRANSIENT = 0x0080,
185 ACC_INTERFACE = 0x0200,
186 ACC_ABSTRACT = 0x0400,
188 ACC_SYNTHETIC = 0x1000,
189 ACC_ANNOTATION = 0x2000,
192 ACC_SUPER = ACC_SYNCHRONIZED,
193 ACC_BRIDGE = ACC_VOLATILE,
194 ACC_VARARGS = ACC_TRANSIENT;
197 * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
200 REF_NONE = 0, // null value
205 REF_invokeVirtual = 5,
206 REF_invokeStatic = 6,
207 REF_invokeSpecial = 7,
208 REF_newInvokeSpecial = 8,
209 REF_invokeInterface = 9,
213 static boolean refKindIsValid(int refKind) {
214 return (refKind > REF_NONE && refKind < REF_LIMIT);
216 static boolean refKindIsField(byte refKind) {
217 assert(refKindIsValid(refKind));
218 return (refKind <= REF_putStatic);
220 static boolean refKindIsGetter(byte refKind) {
221 assert(refKindIsValid(refKind));
222 return (refKind <= REF_getStatic);
224 static boolean refKindIsSetter(byte refKind) {
225 return refKindIsField(refKind) && !refKindIsGetter(refKind);
227 static boolean refKindIsMethod(byte refKind) {
228 return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
230 static boolean refKindIsConstructor(byte refKind) {
231 return (refKind == REF_newInvokeSpecial);
233 static boolean refKindHasReceiver(byte refKind) {
234 assert(refKindIsValid(refKind));
235 return (refKind & 1) != 0;
237 static boolean refKindIsStatic(byte refKind) {
238 return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
240 static boolean refKindDoesDispatch(byte refKind) {
241 assert(refKindIsValid(refKind));
242 return (refKind == REF_invokeVirtual ||
243 refKind == REF_invokeInterface);
246 final int HR_MASK = ((1 << REF_getField) |
247 (1 << REF_putField) |
248 (1 << REF_invokeVirtual) |
249 (1 << REF_invokeSpecial) |
250 (1 << REF_invokeInterface)
252 for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
253 assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
256 static String refKindName(byte refKind) {
257 assert(refKindIsValid(refKind));
259 case REF_getField: return "getField";
260 case REF_getStatic: return "getStatic";
261 case REF_putField: return "putField";
262 case REF_putStatic: return "putStatic";
263 case REF_invokeVirtual: return "invokeVirtual";
264 case REF_invokeStatic: return "invokeStatic";
265 case REF_invokeSpecial: return "invokeSpecial";
266 case REF_newInvokeSpecial: return "newInvokeSpecial";
267 case REF_invokeInterface: return "invokeInterface";
268 default: return "REF_???";
272 private static native int getNamedCon(int which, Object[] name);
273 static boolean verifyConstants() {
274 Object[] box = { null };
275 for (int i = 0; ; i++) {
277 int vmval = getNamedCon(i, box);
278 if (box[0] == null) break;
279 String name = (String) box[0];
281 Field con = Constants.class.getDeclaredField(name);
282 int jval = con.getInt(null);
283 if (jval == vmval) continue;
284 String err = (name+": JVM has "+vmval+" while Java has "+jval);
285 if (name.equals("CONV_OP_LIMIT")) {
286 System.err.println("warning: "+err);
289 throw new InternalError(err);
290 } catch (IllegalAccessException ex) {
291 String err = (name+": JVM has "+vmval+" which Java does not define");
292 // ignore exotic ops the JVM cares about; we just wont issue them
293 //System.err.println("warning: "+err);
300 assert(verifyConstants());
303 // Up-calls from the JVM.
304 // These must NOT be public.
307 * The JVM is linking an invokedynamic instruction. Create a reified call site for it.
309 static MemberName linkCallSite(Object callerObj,
310 Object bootstrapMethodObj,
311 Object nameObj, Object typeObj,
312 Object staticArguments,
313 Object[] appendixResult) {
314 MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
315 Class<?> caller = (Class<?>)callerObj;
316 String name = nameObj.toString().intern();
317 MethodType type = (MethodType)typeObj;
318 CallSite callSite = CallSite.makeSite(bootstrapMethod,
323 if (callSite instanceof ConstantCallSite) {
324 appendixResult[0] = callSite.dynamicInvoker();
325 return Invokers.linkToTargetMethod(type);
327 appendixResult[0] = callSite;
328 return Invokers.linkToCallSiteMethod(type);
333 * The JVM wants a pointer to a MethodType. Oblige it by finding or creating one.
335 static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
336 return MethodType.makeImpl(rtype, ptypes, true);
340 * The JVM wants to link a call site that requires a dynamic type check.
341 * Name is a type-checking invoker, invokeExact or invoke.
342 * Return a JVM method (MemberName) to handle the invoking.
343 * The method assumes the following arguments on the stack:
344 * 0: the method handle being invoked
345 * 1-N: the arguments to the method handle invocation
346 * N+1: an optional, implicitly added argument (typically the given MethodType)
348 * The nominal method at such a call site is an instance of
349 * a signature-polymorphic method (see @PolymorphicSignature).
350 * Such method instances are user-visible entities which are
351 * "split" from the generic placeholder method in {@code MethodHandle}.
352 * (Note that the placeholder method is not identical with any of
353 * its instances. If invoked reflectively, is guaranteed to throw an
354 * {@code UnsupportedOperationException}.)
355 * If the signature-polymorphic method instance is ever reified,
356 * it appears as a "copy" of the original placeholder
357 * (a native final member of {@code MethodHandle}) except
358 * that its type descriptor has shape required by the instance,
359 * and the method instance is <em>not</em> varargs.
360 * The method instance is also marked synthetic, since the
361 * method (by definition) does not appear in Java source code.
363 * The JVM is allowed to reify this method as instance metadata.
364 * For example, {@code invokeBasic} is always reified.
365 * But the JVM may instead call {@code linkMethod}.
366 * If the result is an * ordered pair of a {@code (method, appendix)},
367 * the method gets all the arguments (0..N inclusive)
368 * plus the appendix (N+1), and uses the appendix to complete the call.
369 * In this way, one reusable method (called a "linker method")
370 * can perform the function of any number of polymorphic instance
373 * Linker methods are allowed to be weakly typed, with any or
374 * all references rewritten to {@code Object} and any primitives
375 * (except {@code long}/{@code float}/{@code double})
376 * rewritten to {@code int}.
377 * A linker method is trusted to return a strongly typed result,
378 * according to the specific method type descriptor of the
379 * signature-polymorphic instance it is emulating.
380 * This can involve (as necessary) a dynamic check using
381 * data extracted from the appendix argument.
383 * The JVM does not inspect the appendix, other than to pass
384 * it verbatim to the linker method at every call.
385 * This means that the JDK runtime has wide latitude
386 * for choosing the shape of each linker method and its
387 * corresponding appendix.
388 * Linker methods should be generated from {@code LambdaForm}s
389 * so that they do not become visible on stack traces.
391 * The {@code linkMethod} call is free to omit the appendix
392 * (returning null) and instead emulate the required function
393 * completely in the linker method.
394 * As a corner case, if N==255, no appendix is possible.
395 * In this case, the method returned must be custom-generated to
396 * to perform any needed type checking.
398 * If the JVM does not reify a method at a call site, but instead
399 * calls {@code linkMethod}, the corresponding call represented
400 * in the bytecodes may mention a valid method which is not
401 * representable with a {@code MemberName}.
402 * Therefore, use cases for {@code linkMethod} tend to correspond to
403 * special cases in reflective code such as {@code findVirtual}
404 * or {@code revealDirect}.
406 static MemberName linkMethod(Class<?> callerClass, int refKind,
407 Class<?> defc, String name, Object type,
408 Object[] appendixResult) {
409 if (!TRACE_METHOD_LINKAGE)
410 return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
411 return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
413 static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
414 Class<?> defc, String name, Object type,
415 Object[] appendixResult) {
417 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
418 return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
420 } catch (Throwable ex) {
421 if (ex instanceof LinkageError)
422 throw (LinkageError) ex;
424 throw new LinkageError(ex.getMessage(), ex);
426 throw new LinkageError("no such method "+defc.getName()+"."+name+type);
428 private static MethodType fixMethodType(Class<?> callerClass, Object type) {
429 if (type instanceof MethodType)
430 return (MethodType) type;
432 return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
435 static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
436 Class<?> defc, String name, Object type,
437 Object[] appendixResult) {
438 System.out.println("linkMethod "+defc.getName()+"."+
439 name+type+"/"+Integer.toHexString(refKind));
441 MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
442 System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
444 } catch (Throwable ex) {
445 System.out.println("linkMethod => throw "+ex);
452 * The JVM is resolving a CONSTANT_MethodHandle CP entry. And it wants our help.
453 * It will make an up-call to this method. (Do not change the name or signature.)
454 * The type argument is a Class for field requests and a MethodType for non-fields.
456 * Recent versions of the JVM may also pass a resolved MemberName for the type.
457 * In that case, the name is ignored and may be null.
459 static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
460 Class<?> defc, String name, Object type) {
462 Lookup lookup = IMPL_LOOKUP.in(callerClass);
463 assert(refKindIsValid(refKind));
464 return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
465 } catch (IllegalAccessException ex) {
466 Throwable cause = ex.getCause();
467 if (cause instanceof AbstractMethodError) {
468 throw (AbstractMethodError) cause;
470 Error err = new IllegalAccessError(ex.getMessage());
471 throw initCauseFrom(err, ex);
473 } catch (NoSuchMethodException ex) {
474 Error err = new NoSuchMethodError(ex.getMessage());
475 throw initCauseFrom(err, ex);
476 } catch (NoSuchFieldException ex) {
477 Error err = new NoSuchFieldError(ex.getMessage());
478 throw initCauseFrom(err, ex);
479 } catch (ReflectiveOperationException ex) {
480 Error err = new IncompatibleClassChangeError();
481 throw initCauseFrom(err, ex);
486 * Use best possible cause for err.initCause(), substituting the
487 * cause for err itself if the cause has the same (or better) type.
489 static private Error initCauseFrom(Error err, Exception ex) {
490 Throwable th = ex.getCause();
491 if (err.getClass().isInstance(th))
493 err.initCause(th == null ? ex : th);
498 * Is this method a caller-sensitive method?
499 * I.e., does it call Reflection.getCallerClass or a similer method
500 * to ask about the identity of its caller?
502 static boolean isCallerSensitive(MemberName mem) {
503 if (!mem.isInvocable()) return false; // fields are not caller sensitive
505 return mem.isCallerSensitive() || canBeCalledVirtual(mem);
508 static boolean canBeCalledVirtual(MemberName mem) {
509 assert(mem.isInvocable());
510 Class<?> defc = mem.getDeclaringClass();
511 switch (mem.getName()) {
512 case "checkMemberAccess":
513 return true; //canBeCalledVirtual(mem, java.lang.SecurityManager.class);
514 case "getContextClassLoader":
515 return canBeCalledVirtual(mem, java.lang.Thread.class);
520 static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
521 Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
522 if (symbolicRefClass == definingClass) return true;
523 if (symbolicRef.isStatic() || symbolicRef.isPrivate()) return false;
524 return (definingClass.isAssignableFrom(symbolicRefClass) || // Msym overrides Mdef
525 symbolicRefClass.isInterface()); // Mdef implements Msym