Need to initialize flags. getFields throws SecurityException on bck2brwsr VM - avoid.
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 final Member mem = (Member)ref;
51 self.clazz = mem.getDeclaringClass();
52 int mod = mem.getModifiers();
53 if (ref instanceof Method) {
54 mod |= MemberName.IS_METHOD;
56 if (ref instanceof Constructor) {
57 mod |= MemberName.IS_CONSTRUCTOR;
62 static void expand(MemberName self) {
65 static MemberName resolve(MemberName self, Class<?> caller) throws LinkageError {
68 static int getMembers(Class<?> defc, String matchName, String matchSig,
69 int matchFlags, Class<?> caller, int skip, MemberName[] results) {
71 for (Method m : defc.getMethods()) {
72 if (skip == results.length) {
75 MemberName mn = new MemberName(m);
78 for (Constructor m : defc.getConstructors()) {
79 if (skip == results.length) {
82 MemberName mn = new MemberName(m);
85 // for (Field m : defc.getFields()) {
86 // if (skip == results.length) {
89 // MemberName mn = new MemberName(m);
90 // results[skip++] = mn;
95 /// Field layout queries parallel to sun.misc.Unsafe:
96 static native long objectFieldOffset(MemberName self); // e.g., returns vmindex
97 static native long staticFieldOffset(MemberName self); // e.g., returns vmindex
98 static native Object staticFieldBase(MemberName self); // e.g., returns clazz
99 static native Object getMemberVMInfo(MemberName self); // returns {vmindex,vmtarget}
101 /// MethodHandle support
105 /** Tell the JVM that we need to change the target of a CallSite. */
106 static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
107 static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
110 // The JVM calls MethodHandleNatives.<clinit>. Cascade the <clinit> calls as needed:
111 MethodHandleImpl.initStatics();
114 // All compile-time constants go here.
115 // There is an opportunity to check them against the JVM's idea of them.
116 static class Constants {
117 Constants() { } // static only
119 static final int // for getConstant
121 GC_LAMBDA_SUPPORT = 5;
124 // The JVM uses values of -2 and above for vtable indexes.
125 // Field values are simple positive offsets.
126 // Ref: src/share/vm/oops/methodOop.hpp
127 // This value is negative enough to avoid such numbers,
128 // but not too negative.
130 MN_IS_METHOD = 0x00010000, // method (not constructor)
131 MN_IS_CONSTRUCTOR = 0x00020000, // constructor
132 MN_IS_FIELD = 0x00040000, // field
133 MN_IS_TYPE = 0x00080000, // nested type
134 MN_CALLER_SENSITIVE = 0x00100000, // @CallerSensitive annotation detected
135 MN_REFERENCE_KIND_SHIFT = 24, // refKind
136 MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
137 // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
138 MN_SEARCH_SUPERCLASSES = 0x00100000,
139 MN_SEARCH_INTERFACES = 0x00200000;
142 * Basic types as encoded in the JVM. These code values are not
143 * intended for use outside this class. They are used as part of
144 * a private interface between the JVM and this class.
162 * Constant pool entry types.
166 CONSTANT_Integer = 3,
172 CONSTANT_Fieldref = 9,
173 CONSTANT_Methodref = 10,
174 CONSTANT_InterfaceMethodref = 11,
175 CONSTANT_NameAndType = 12,
176 CONSTANT_MethodHandle = 15, // JSR 292
177 CONSTANT_MethodType = 16, // JSR 292
178 CONSTANT_InvokeDynamic = 18,
179 CONSTANT_LIMIT = 19; // Limit to tags found in classfiles
182 * Access modifier flags.
186 ACC_PRIVATE = 0x0002,
187 ACC_PROTECTED = 0x0004,
190 ACC_SYNCHRONIZED = 0x0020,
191 ACC_VOLATILE = 0x0040,
192 ACC_TRANSIENT = 0x0080,
194 ACC_INTERFACE = 0x0200,
195 ACC_ABSTRACT = 0x0400,
197 ACC_SYNTHETIC = 0x1000,
198 ACC_ANNOTATION = 0x2000,
201 ACC_SUPER = ACC_SYNCHRONIZED,
202 ACC_BRIDGE = ACC_VOLATILE,
203 ACC_VARARGS = ACC_TRANSIENT;
206 * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
209 REF_NONE = 0, // null value
214 REF_invokeVirtual = 5,
215 REF_invokeStatic = 6,
216 REF_invokeSpecial = 7,
217 REF_newInvokeSpecial = 8,
218 REF_invokeInterface = 9,
222 static boolean refKindIsValid(int refKind) {
223 return (refKind > REF_NONE && refKind < REF_LIMIT);
225 static boolean refKindIsField(byte refKind) {
226 assert(refKindIsValid(refKind));
227 return (refKind <= REF_putStatic);
229 static boolean refKindIsGetter(byte refKind) {
230 assert(refKindIsValid(refKind));
231 return (refKind <= REF_getStatic);
233 static boolean refKindIsSetter(byte refKind) {
234 return refKindIsField(refKind) && !refKindIsGetter(refKind);
236 static boolean refKindIsMethod(byte refKind) {
237 return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
239 static boolean refKindIsConstructor(byte refKind) {
240 return (refKind == REF_newInvokeSpecial);
242 static boolean refKindHasReceiver(byte refKind) {
243 assert(refKindIsValid(refKind));
244 return (refKind & 1) != 0;
246 static boolean refKindIsStatic(byte refKind) {
247 return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
249 static boolean refKindDoesDispatch(byte refKind) {
250 assert(refKindIsValid(refKind));
251 return (refKind == REF_invokeVirtual ||
252 refKind == REF_invokeInterface);
255 final int HR_MASK = ((1 << REF_getField) |
256 (1 << REF_putField) |
257 (1 << REF_invokeVirtual) |
258 (1 << REF_invokeSpecial) |
259 (1 << REF_invokeInterface)
261 for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
262 assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
265 static String refKindName(byte refKind) {
266 assert(refKindIsValid(refKind));
268 case REF_getField: return "getField";
269 case REF_getStatic: return "getStatic";
270 case REF_putField: return "putField";
271 case REF_putStatic: return "putStatic";
272 case REF_invokeVirtual: return "invokeVirtual";
273 case REF_invokeStatic: return "invokeStatic";
274 case REF_invokeSpecial: return "invokeSpecial";
275 case REF_newInvokeSpecial: return "newInvokeSpecial";
276 case REF_invokeInterface: return "invokeInterface";
277 default: return "REF_???";
281 private static native int getNamedCon(int which, Object[] name);
282 static boolean verifyConstants() {
283 Object[] box = { null };
284 for (int i = 0; ; i++) {
286 int vmval = getNamedCon(i, box);
287 if (box[0] == null) break;
288 String name = (String) box[0];
290 Field con = Constants.class.getDeclaredField(name);
291 int jval = con.getInt(null);
292 if (jval == vmval) continue;
293 String err = (name+": JVM has "+vmval+" while Java has "+jval);
294 if (name.equals("CONV_OP_LIMIT")) {
295 System.err.println("warning: "+err);
298 throw new InternalError(err);
299 } catch (IllegalAccessException ex) {
300 String err = (name+": JVM has "+vmval+" which Java does not define");
301 // ignore exotic ops the JVM cares about; we just wont issue them
302 //System.err.println("warning: "+err);
309 assert(verifyConstants());
312 // Up-calls from the JVM.
313 // These must NOT be public.
316 * The JVM is linking an invokedynamic instruction. Create a reified call site for it.
318 static MemberName linkCallSite(Object callerObj,
319 Object bootstrapMethodObj,
320 Object nameObj, Object typeObj,
321 Object staticArguments,
322 Object[] appendixResult) {
323 MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
324 Class<?> caller = (Class<?>)callerObj;
325 String name = nameObj.toString().intern();
326 MethodType type = (MethodType)typeObj;
327 CallSite callSite = CallSite.makeSite(bootstrapMethod,
332 if (callSite instanceof ConstantCallSite) {
333 appendixResult[0] = callSite.dynamicInvoker();
334 return Invokers.linkToTargetMethod(type);
336 appendixResult[0] = callSite;
337 return Invokers.linkToCallSiteMethod(type);
342 * The JVM wants a pointer to a MethodType. Oblige it by finding or creating one.
344 static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
345 return MethodType.makeImpl(rtype, ptypes, true);
349 * The JVM wants to link a call site that requires a dynamic type check.
350 * Name is a type-checking invoker, invokeExact or invoke.
351 * Return a JVM method (MemberName) to handle the invoking.
352 * The method assumes the following arguments on the stack:
353 * 0: the method handle being invoked
354 * 1-N: the arguments to the method handle invocation
355 * N+1: an optional, implicitly added argument (typically the given MethodType)
357 * The nominal method at such a call site is an instance of
358 * a signature-polymorphic method (see @PolymorphicSignature).
359 * Such method instances are user-visible entities which are
360 * "split" from the generic placeholder method in {@code MethodHandle}.
361 * (Note that the placeholder method is not identical with any of
362 * its instances. If invoked reflectively, is guaranteed to throw an
363 * {@code UnsupportedOperationException}.)
364 * If the signature-polymorphic method instance is ever reified,
365 * it appears as a "copy" of the original placeholder
366 * (a native final member of {@code MethodHandle}) except
367 * that its type descriptor has shape required by the instance,
368 * and the method instance is <em>not</em> varargs.
369 * The method instance is also marked synthetic, since the
370 * method (by definition) does not appear in Java source code.
372 * The JVM is allowed to reify this method as instance metadata.
373 * For example, {@code invokeBasic} is always reified.
374 * But the JVM may instead call {@code linkMethod}.
375 * If the result is an * ordered pair of a {@code (method, appendix)},
376 * the method gets all the arguments (0..N inclusive)
377 * plus the appendix (N+1), and uses the appendix to complete the call.
378 * In this way, one reusable method (called a "linker method")
379 * can perform the function of any number of polymorphic instance
382 * Linker methods are allowed to be weakly typed, with any or
383 * all references rewritten to {@code Object} and any primitives
384 * (except {@code long}/{@code float}/{@code double})
385 * rewritten to {@code int}.
386 * A linker method is trusted to return a strongly typed result,
387 * according to the specific method type descriptor of the
388 * signature-polymorphic instance it is emulating.
389 * This can involve (as necessary) a dynamic check using
390 * data extracted from the appendix argument.
392 * The JVM does not inspect the appendix, other than to pass
393 * it verbatim to the linker method at every call.
394 * This means that the JDK runtime has wide latitude
395 * for choosing the shape of each linker method and its
396 * corresponding appendix.
397 * Linker methods should be generated from {@code LambdaForm}s
398 * so that they do not become visible on stack traces.
400 * The {@code linkMethod} call is free to omit the appendix
401 * (returning null) and instead emulate the required function
402 * completely in the linker method.
403 * As a corner case, if N==255, no appendix is possible.
404 * In this case, the method returned must be custom-generated to
405 * to perform any needed type checking.
407 * If the JVM does not reify a method at a call site, but instead
408 * calls {@code linkMethod}, the corresponding call represented
409 * in the bytecodes may mention a valid method which is not
410 * representable with a {@code MemberName}.
411 * Therefore, use cases for {@code linkMethod} tend to correspond to
412 * special cases in reflective code such as {@code findVirtual}
413 * or {@code revealDirect}.
415 static MemberName linkMethod(Class<?> callerClass, int refKind,
416 Class<?> defc, String name, Object type,
417 Object[] appendixResult) {
418 if (!TRACE_METHOD_LINKAGE)
419 return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
420 return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
422 static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
423 Class<?> defc, String name, Object type,
424 Object[] appendixResult) {
426 if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
427 return Invokers.methodHandleInvokeLinkerMethod(name, fixMethodType(callerClass, type), appendixResult);
429 } catch (Throwable ex) {
430 if (ex instanceof LinkageError)
431 throw (LinkageError) ex;
433 throw new LinkageError(ex.getMessage(), ex);
435 throw new LinkageError("no such method "+defc.getName()+"."+name+type);
437 private static MethodType fixMethodType(Class<?> callerClass, Object type) {
438 if (type instanceof MethodType)
439 return (MethodType) type;
441 return MethodType.fromMethodDescriptorString((String)type, callerClass.getClassLoader());
444 static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
445 Class<?> defc, String name, Object type,
446 Object[] appendixResult) {
447 System.out.println("linkMethod "+defc.getName()+"."+
448 name+type+"/"+Integer.toHexString(refKind));
450 MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
451 System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
453 } catch (Throwable ex) {
454 System.out.println("linkMethod => throw "+ex);
461 * The JVM is resolving a CONSTANT_MethodHandle CP entry. And it wants our help.
462 * It will make an up-call to this method. (Do not change the name or signature.)
463 * The type argument is a Class for field requests and a MethodType for non-fields.
465 * Recent versions of the JVM may also pass a resolved MemberName for the type.
466 * In that case, the name is ignored and may be null.
468 static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
469 Class<?> defc, String name, Object type) {
471 Lookup lookup = IMPL_LOOKUP.in(callerClass);
472 assert(refKindIsValid(refKind));
473 return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
474 } catch (IllegalAccessException ex) {
475 Throwable cause = ex.getCause();
476 if (cause instanceof AbstractMethodError) {
477 throw (AbstractMethodError) cause;
479 Error err = new IllegalAccessError(ex.getMessage());
480 throw initCauseFrom(err, ex);
482 } catch (NoSuchMethodException ex) {
483 Error err = new NoSuchMethodError(ex.getMessage());
484 throw initCauseFrom(err, ex);
485 } catch (NoSuchFieldException ex) {
486 Error err = new NoSuchFieldError(ex.getMessage());
487 throw initCauseFrom(err, ex);
488 } catch (ReflectiveOperationException ex) {
489 Error err = new IncompatibleClassChangeError();
490 throw initCauseFrom(err, ex);
495 * Use best possible cause for err.initCause(), substituting the
496 * cause for err itself if the cause has the same (or better) type.
498 static private Error initCauseFrom(Error err, Exception ex) {
499 Throwable th = ex.getCause();
500 if (err.getClass().isInstance(th))
502 err.initCause(th == null ? ex : th);
507 * Is this method a caller-sensitive method?
508 * I.e., does it call Reflection.getCallerClass or a similer method
509 * to ask about the identity of its caller?
511 static boolean isCallerSensitive(MemberName mem) {
512 if (!mem.isInvocable()) return false; // fields are not caller sensitive
514 return mem.isCallerSensitive() || canBeCalledVirtual(mem);
517 static boolean canBeCalledVirtual(MemberName mem) {
518 assert(mem.isInvocable());
519 Class<?> defc = mem.getDeclaringClass();
520 switch (mem.getName()) {
521 case "checkMemberAccess":
522 return true; //canBeCalledVirtual(mem, java.lang.SecurityManager.class);
523 case "getContextClassLoader":
524 return canBeCalledVirtual(mem, java.lang.Thread.class);
529 static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
530 Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
531 if (symbolicRefClass == definingClass) return true;
532 if (symbolicRef.isStatic() || symbolicRef.isPrivate()) return false;
533 return (definingClass.isAssignableFrom(symbolicRefClass) || // Msym overrides Mdef
534 symbolicRefClass.isInterface()); // Mdef implements Msym