1 /*
   2  * Copyright (c) 2008, 2015, 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.invoke;
  27 
  28 import jdk.internal.ref.CleanerFactory;
  29 import sun.invoke.util.Wrapper;
  30 
  31 import java.lang.invoke.MethodHandles.Lookup;
  32 import java.lang.reflect.Field;
  33 
  34 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  35 import static java.lang.invoke.MethodHandleStatics.TRACE_METHOD_LINKAGE;
  36 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  37 
  38 /**
  39  * The JVM interface for the method handles package is all here.
  40  * This is an interface internal and private to an implementation of JSR 292.
  41  * <em>This class is not part of the JSR 292 standard.</em>
  42  * @author jrose
  43  */
  44 class MethodHandleNatives {
  45 
  46     private MethodHandleNatives() { } // static only
  47 
  48     /// MemberName support
  49 
  50     static native void init(MemberName self, Object ref);
  51     static native void expand(MemberName self);
  52     static native MemberName resolve(MemberName self, Class<?> caller) throws LinkageError, ClassNotFoundException;
  53     static native int getMembers(Class<?> defc, String matchName, String matchSig,
  54             int matchFlags, Class<?> caller, int skip, MemberName[] results);
  55 
  56     /// Field layout queries parallel to jdk.internal.misc.Unsafe:
  57     static native long objectFieldOffset(MemberName self);  // e.g., returns vmindex
  58     static native long staticFieldOffset(MemberName self);  // e.g., returns vmindex
  59     static native Object staticFieldBase(MemberName self);  // e.g., returns clazz
  60     static native Object getMemberVMInfo(MemberName self);  // returns {vmindex,vmtarget}
  61 
  62     /// CallSite support
  63 
  64     /** Tell the JVM that we need to change the target of a CallSite. */
  65     static native void setCallSiteTargetNormal(CallSite site, MethodHandle target);
  66     static native void setCallSiteTargetVolatile(CallSite site, MethodHandle target);
  67 
  68     private static boolean MSOK;
  69     static boolean moduleSystemInitialized() {
  70         if (MSOK)  return true;
  71         //if (java.lang.reflect.Layer.boot() == null)  return false;
  72         try {
  73             Class<?> C_Layer = Class.forName("java.lang.reflect.Layer");
  74             if (C_Layer.getDeclaredMethod("boot").invoke(null) == null)
  75                 return false;
  76         } catch (ReflectiveOperationException ex) {
  77             return false;
  78         }
  79         MSOK = true;
  80         return true;
  81     }
  82 
  83     /** Represents a context to track nmethod dependencies on CallSite instance target. */
  84     static class CallSiteContext implements Runnable {
  85         //@Injected JVM_nmethodBucket* vmdependencies;
  86 
  87         static CallSiteContext make(CallSite cs) {
  88             final CallSiteContext newContext = new CallSiteContext();
  89             // CallSite instance is tracked by a Cleanable which clears native
  90             // structures allocated for CallSite context. Though the CallSite can
  91             // become unreachable, its Context is retained by the Cleanable instance
  92             // (which is referenced from Cleaner instance which is referenced from
  93             // CleanerFactory class) until cleanup is performed.
  94             CleanerFactory.cleaner().register(cs, newContext);
  95             return newContext;
  96         }
  97 
  98         @Override
  99         public void run() {
 100             MethodHandleNatives.clearCallSiteContext(this);
 101         }
 102     }
 103 
 104     /** Invalidate all recorded nmethods. */
 105     private static native void clearCallSiteContext(CallSiteContext context);
 106 
 107     private static native void registerNatives();
 108     static {
 109         registerNatives();
 110     }
 111 
 112     /**
 113      * Compile-time constants go here. This collection exists not only for
 114      * reference from clients, but also for ensuring the VM and JDK agree on the
 115      * values of these constants (see {@link #verifyConstants()}).
 116      */
 117     static class Constants {
 118         Constants() { } // static only
 119 
 120         static final int
 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;
 131 
 132         /**
 133          * Constant pool reference-kind codes, as used by CONSTANT_MethodHandle CP entries.
 134          */
 135         static final byte
 136             REF_NONE                    = 0,  // null value
 137             REF_getField                = 1,
 138             REF_getStatic               = 2,
 139             REF_putField                = 3,
 140             REF_putStatic               = 4,
 141             REF_invokeVirtual           = 5,
 142             REF_invokeStatic            = 6,
 143             REF_invokeSpecial           = 7,
 144             REF_newInvokeSpecial        = 8,
 145             REF_invokeInterface         = 9,
 146             REF_LIMIT                  = 10;
 147     }
 148 
 149     static boolean refKindIsValid(int refKind) {
 150         return (refKind > REF_NONE && refKind < REF_LIMIT);
 151     }
 152     static boolean refKindIsField(byte refKind) {
 153         assert(refKindIsValid(refKind));
 154         return (refKind <= REF_putStatic);
 155     }
 156     static boolean refKindIsGetter(byte refKind) {
 157         assert(refKindIsValid(refKind));
 158         return (refKind <= REF_getStatic);
 159     }
 160     static boolean refKindIsSetter(byte refKind) {
 161         return refKindIsField(refKind) && !refKindIsGetter(refKind);
 162     }
 163     static boolean refKindIsMethod(byte refKind) {
 164         return !refKindIsField(refKind) && (refKind != REF_newInvokeSpecial);
 165     }
 166     static boolean refKindIsConstructor(byte refKind) {
 167         return (refKind == REF_newInvokeSpecial);
 168     }
 169     static boolean refKindHasReceiver(byte refKind) {
 170         assert(refKindIsValid(refKind));
 171         return (refKind & 1) != 0;
 172     }
 173     static boolean refKindIsStatic(byte refKind) {
 174         return !refKindHasReceiver(refKind) && (refKind != REF_newInvokeSpecial);
 175     }
 176     static boolean refKindDoesDispatch(byte refKind) {
 177         assert(refKindIsValid(refKind));
 178         return (refKind == REF_invokeVirtual ||
 179                 refKind == REF_invokeInterface);
 180     }
 181     static {
 182         final int HR_MASK = ((1 << REF_getField) |
 183                              (1 << REF_putField) |
 184                              (1 << REF_invokeVirtual) |
 185                              (1 << REF_invokeSpecial) |
 186                              (1 << REF_invokeInterface)
 187                             );
 188         for (byte refKind = REF_NONE+1; refKind < REF_LIMIT; refKind++) {
 189             assert(refKindHasReceiver(refKind) == (((1<<refKind) & HR_MASK) != 0)) : refKind;
 190         }
 191     }
 192     static String refKindName(byte refKind) {
 193         assert(refKindIsValid(refKind));
 194         switch (refKind) {
 195         case REF_getField:          return "getField";
 196         case REF_getStatic:         return "getStatic";
 197         case REF_putField:          return "putField";
 198         case REF_putStatic:         return "putStatic";
 199         case REF_invokeVirtual:     return "invokeVirtual";
 200         case REF_invokeStatic:      return "invokeStatic";
 201         case REF_invokeSpecial:     return "invokeSpecial";
 202         case REF_newInvokeSpecial:  return "newInvokeSpecial";
 203         case REF_invokeInterface:   return "invokeInterface";
 204         default:                    return "REF_???";
 205         }
 206     }
 207 
 208     private static native int getNamedCon(int which, Object[] name);
 209     static boolean verifyConstants() {
 210         Object[] box = { null };
 211         for (int i = 0; ; i++) {
 212             box[0] = null;
 213             int vmval = getNamedCon(i, box);
 214             if (box[0] == null)  break;
 215             String name = (String) box[0];
 216             try {
 217                 Field con = Constants.class.getDeclaredField(name);
 218                 int jval = con.getInt(null);
 219                 if (jval == vmval)  continue;
 220                 String err = (name+": JVM has "+vmval+" while Java has "+jval);
 221                 if (name.equals("CONV_OP_LIMIT")) {
 222                     System.err.println("warning: "+err);
 223                     continue;
 224                 }
 225                 throw new InternalError(err);
 226             } catch (NoSuchFieldException | IllegalAccessException ex) {
 227                 String err = (name+": JVM has "+vmval+" which Java does not define");
 228                 // ignore exotic ops the JVM cares about; we just wont issue them
 229                 //System.err.println("warning: "+err);
 230                 continue;
 231             }
 232         }
 233         return true;
 234     }
 235     static {
 236         assert(verifyConstants());
 237     }
 238 
 239     // Up-calls from the JVM.
 240     // These must NOT be public.
 241 
 242     /**
 243      * The JVM is linking an invokedynamic instruction.  Create a reified call site for it.
 244      */
 245     static MemberName linkCallSite(Object callerObj,
 246                                    Object bootstrapMethodObj,
 247                                    Object nameObj, Object typeObj,
 248                                    Object staticArguments,
 249                                    Object[] appendixResult) {
 250         MethodHandle bootstrapMethod = (MethodHandle)bootstrapMethodObj;
 251         Class<?> caller = (Class<?>)callerObj;
 252         String name = nameObj.toString().intern();
 253         MethodType type = (MethodType)typeObj;
 254         if (!TRACE_METHOD_LINKAGE)
 255             return linkCallSiteImpl(caller, bootstrapMethod, name, type,
 256                                     staticArguments, appendixResult);
 257         return linkCallSiteTracing(caller, bootstrapMethod, name, type,
 258                                    staticArguments, appendixResult);
 259     }
 260     static MemberName linkCallSiteImpl(Class<?> caller,
 261                                        MethodHandle bootstrapMethod,
 262                                        String name, MethodType type,
 263                                        Object staticArguments,
 264                                        Object[] appendixResult) {
 265         CallSite callSite = CallSite.makeSite(bootstrapMethod,
 266                                               name,
 267                                               type,
 268                                               staticArguments,
 269                                               caller);
 270         if (callSite instanceof ConstantCallSite) {
 271             appendixResult[0] = callSite.dynamicInvoker();
 272             return Invokers.linkToTargetMethod(type);
 273         } else {
 274             appendixResult[0] = callSite;
 275             return Invokers.linkToCallSiteMethod(type);
 276         }
 277     }
 278     // Tracing logic:
 279     static MemberName linkCallSiteTracing(Class<?> caller,
 280                                           MethodHandle bootstrapMethod,
 281                                           String name, MethodType type,
 282                                           Object staticArguments,
 283                                           Object[] appendixResult) {
 284         Object bsmReference = bootstrapMethod.internalMemberName();
 285         if (bsmReference == null)  bsmReference = bootstrapMethod;
 286         Object staticArglist = (staticArguments instanceof Object[] ?
 287                                 java.util.Arrays.asList((Object[]) staticArguments) :
 288                                 staticArguments);
 289         System.out.println("linkCallSite "+caller.getName()+" "+
 290                            bsmReference+" "+
 291                            name+type+"/"+staticArglist);
 292         try {
 293             MemberName res = linkCallSiteImpl(caller, bootstrapMethod, name, type,
 294                                               staticArguments, appendixResult);
 295             System.out.println("linkCallSite => "+res+" + "+appendixResult[0]);
 296             return res;
 297         } catch (Throwable ex) {
 298             System.out.println("linkCallSite => throw "+ex);
 299             throw ex;
 300         }
 301     }
 302 
 303     /**
 304      * The JVM wants a pointer to a MethodType.  Oblige it by finding or creating one.
 305      */
 306     static MethodType findMethodHandleType(Class<?> rtype, Class<?>[] ptypes) {
 307         return MethodType.makeImpl(rtype, ptypes, true);
 308     }
 309 
 310     /**
 311      * The JVM wants to link a call site that requires a dynamic type check.
 312      * Name is a type-checking invoker, invokeExact or invoke.
 313      * Return a JVM method (MemberName) to handle the invoking.
 314      * The method assumes the following arguments on the stack:
 315      * 0: the method handle being invoked
 316      * 1-N: the arguments to the method handle invocation
 317      * N+1: an optional, implicitly added argument (typically the given MethodType)
 318      * <p>
 319      * The nominal method at such a call site is an instance of
 320      * a signature-polymorphic method (see @PolymorphicSignature).
 321      * Such method instances are user-visible entities which are
 322      * "split" from the generic placeholder method in {@code MethodHandle}.
 323      * (Note that the placeholder method is not identical with any of
 324      * its instances.  If invoked reflectively, is guaranteed to throw an
 325      * {@code UnsupportedOperationException}.)
 326      * If the signature-polymorphic method instance is ever reified,
 327      * it appears as a "copy" of the original placeholder
 328      * (a native final member of {@code MethodHandle}) except
 329      * that its type descriptor has shape required by the instance,
 330      * and the method instance is <em>not</em> varargs.
 331      * The method instance is also marked synthetic, since the
 332      * method (by definition) does not appear in Java source code.
 333      * <p>
 334      * The JVM is allowed to reify this method as instance metadata.
 335      * For example, {@code invokeBasic} is always reified.
 336      * But the JVM may instead call {@code linkMethod}.
 337      * If the result is an * ordered pair of a {@code (method, appendix)},
 338      * the method gets all the arguments (0..N inclusive)
 339      * plus the appendix (N+1), and uses the appendix to complete the call.
 340      * In this way, one reusable method (called a "linker method")
 341      * can perform the function of any number of polymorphic instance
 342      * methods.
 343      * <p>
 344      * Linker methods are allowed to be weakly typed, with any or
 345      * all references rewritten to {@code Object} and any primitives
 346      * (except {@code long}/{@code float}/{@code double})
 347      * rewritten to {@code int}.
 348      * A linker method is trusted to return a strongly typed result,
 349      * according to the specific method type descriptor of the
 350      * signature-polymorphic instance it is emulating.
 351      * This can involve (as necessary) a dynamic check using
 352      * data extracted from the appendix argument.
 353      * <p>
 354      * The JVM does not inspect the appendix, other than to pass
 355      * it verbatim to the linker method at every call.
 356      * This means that the JDK runtime has wide latitude
 357      * for choosing the shape of each linker method and its
 358      * corresponding appendix.
 359      * Linker methods should be generated from {@code LambdaForm}s
 360      * so that they do not become visible on stack traces.
 361      * <p>
 362      * The {@code linkMethod} call is free to omit the appendix
 363      * (returning null) and instead emulate the required function
 364      * completely in the linker method.
 365      * As a corner case, if N==255, no appendix is possible.
 366      * In this case, the method returned must be custom-generated to
 367      * to perform any needed type checking.
 368      * <p>
 369      * If the JVM does not reify a method at a call site, but instead
 370      * calls {@code linkMethod}, the corresponding call represented
 371      * in the bytecodes may mention a valid method which is not
 372      * representable with a {@code MemberName}.
 373      * Therefore, use cases for {@code linkMethod} tend to correspond to
 374      * special cases in reflective code such as {@code findVirtual}
 375      * or {@code revealDirect}.
 376      */
 377     static MemberName linkMethod(Class<?> callerClass, int refKind,
 378                                  Class<?> defc, String name, Object type,
 379                                  Object[] appendixResult) {
 380         if (!TRACE_METHOD_LINKAGE)
 381             return linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 382         return linkMethodTracing(callerClass, refKind, defc, name, type, appendixResult);
 383     }
 384     static MemberName linkMethodImpl(Class<?> callerClass, int refKind,
 385                                      Class<?> defc, String name, Object type,
 386                                      Object[] appendixResult) {
 387         try {
 388             if (refKind == REF_invokeVirtual) {
 389                 if (defc == MethodHandle.class) {
 390                     return Invokers.methodHandleInvokeLinkerMethod(
 391                             name, fixMethodType(callerClass, type), appendixResult);
 392                 } else if (defc == VarHandle.class) {
 393                     return varHandleOperationLinkerMethod(
 394                             name, fixMethodType(callerClass, type), appendixResult);
 395                 }
 396             }
 397         } catch (Error e) {
 398             // Pass through an Error, including say StackOverflowError or
 399             // OutOfMemoryError
 400             throw e;
 401         } catch (Throwable ex) {
 402             // Wrap anything else in LinkageError
 403             throw new LinkageError(ex.getMessage(), ex);
 404         }
 405         throw new LinkageError("no such method "+defc.getName()+"."+name+type);
 406     }
 407     private static MethodType fixMethodType(Class<?> callerClass, Object type) {
 408         if (type instanceof MethodType)
 409             return (MethodType) type;
 410         else
 411             return MethodType.fromDescriptor((String)type, callerClass.getClassLoader());
 412     }
 413     // Tracing logic:
 414     static MemberName linkMethodTracing(Class<?> callerClass, int refKind,
 415                                         Class<?> defc, String name, Object type,
 416                                         Object[] appendixResult) {
 417         System.out.println("linkMethod "+defc.getName()+"."+
 418                            name+type+"/"+Integer.toHexString(refKind));
 419         try {
 420             MemberName res = linkMethodImpl(callerClass, refKind, defc, name, type, appendixResult);
 421             System.out.println("linkMethod => "+res+" + "+appendixResult[0]);
 422             return res;
 423         } catch (Throwable ex) {
 424             System.out.println("linkMethod => throw "+ex);
 425             throw ex;
 426         }
 427     }
 428 
 429     /**
 430      * Obtain the method to link to the VarHandle operation.
 431      * This method is located here and not in Invokers to avoid
 432      * intializing that and other classes early on in VM bootup.
 433      */
 434     private static MemberName varHandleOperationLinkerMethod(String name,
 435                                                              MethodType mtype,
 436                                                              Object[] appendixResult) {
 437         // Get the signature method type
 438         final MethodType sigType = mtype.basicType();
 439 
 440         // Get the access kind from the method name
 441         VarHandle.AccessMode ak;
 442         try {
 443             ak = VarHandle.AccessMode.valueFromMethodName(name);
 444         } catch (IllegalArgumentException e) {
 445             throw MethodHandleStatics.newInternalError(e);
 446         }
 447 
 448         // Create the appendix descriptor constant
 449         VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal());
 450         appendixResult[0] = ad;
 451 
 452         if (MethodHandleStatics.VAR_HANDLE_GUARDS) {
 453             // If not polymorphic in the return type, such as the compareAndSet
 454             // methods that return boolean
 455             Class<?> guardReturnType = sigType.returnType();
 456             if (ak.at.isMonomorphicInReturnType) {
 457                 if (ak.at.returnType != mtype.returnType()) {
 458                     // The caller contains a different return type than that
 459                     // defined by the method
 460                     throw newNoSuchMethodErrorOnVarHandle(name, mtype);
 461                 }
 462                 // Adjust the return type of the signature method type
 463                 guardReturnType = ak.at.returnType;
 464             }
 465 
 466             // Get the guard method type for linking
 467             final Class<?>[] guardParams = new Class<?>[sigType.parameterCount() + 2];
 468             // VarHandle at start
 469             guardParams[0] = VarHandle.class;
 470             for (int i = 0; i < sigType.parameterCount(); i++) {
 471                 guardParams[i + 1] = sigType.parameterType(i);
 472             }
 473             // Access descriptor at end
 474             guardParams[guardParams.length - 1] = VarHandle.AccessDescriptor.class;
 475             MethodType guardType = MethodType.makeImpl(guardReturnType, guardParams, true);
 476 
 477             MemberName linker = new MemberName(
 478                     VarHandleGuards.class, getVarHandleGuardMethodName(guardType),
 479                     guardType, REF_invokeStatic);
 480 
 481             linker = MemberName.getFactory().resolveOrNull(REF_invokeStatic, linker,
 482                                                            VarHandleGuards.class);
 483             if (linker != null) {
 484                 return linker;
 485             }
 486             // Fall back to lambda form linkage if guard method is not available
 487             // TODO Optionally log fallback ?
 488         }
 489         return Invokers.varHandleInvokeLinkerMethod(ak, mtype);
 490     }
 491     static String getVarHandleGuardMethodName(MethodType guardType) {
 492         String prefix = "guard_";
 493         StringBuilder sb = new StringBuilder(prefix.length() + guardType.parameterCount());
 494 
 495         sb.append(prefix);
 496         for (int i = 1; i < guardType.parameterCount() - 1; i++) {
 497             Class<?> pt = guardType.parameterType(i);
 498             sb.append(getCharType(pt));
 499         }
 500         sb.append('_').append(getCharType(guardType.returnType()));
 501         return sb.toString();
 502     }
 503     static char getCharType(Class<?> pt) {
 504         return Wrapper.forBasicType(pt).basicTypeChar();
 505     }
 506     static NoSuchMethodError newNoSuchMethodErrorOnVarHandle(String name, MethodType mtype) {
 507         return new NoSuchMethodError("VarHandle." + name + mtype);
 508     }
 509 
 510     /**
 511      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
 512      * It will make an up-call to this method.  (Do not change the name or signature.)
 513      * The type argument is a Class for field requests and a MethodType for non-fields.
 514      * <p>
 515      * Recent versions of the JVM may also pass a resolved MemberName for the type.
 516      * In that case, the name is ignored and may be null.
 517      */
 518     static MethodHandle linkMethodHandleConstant(Class<?> callerClass, int refKind,
 519                                                  Class<?> defc, String name, Object type) {
 520         try {
 521             Lookup lookup = IMPL_LOOKUP.in(callerClass);
 522             assert(refKindIsValid(refKind));
 523             return lookup.linkMethodHandleConstant((byte) refKind, defc, name, type);
 524         } catch (IllegalAccessException ex) {
 525             Throwable cause = ex.getCause();
 526             if (cause instanceof AbstractMethodError) {
 527                 throw (AbstractMethodError) cause;
 528             } else {
 529                 Error err = new IllegalAccessError(ex.getMessage());
 530                 throw initCauseFrom(err, ex);
 531             }
 532         } catch (NoSuchMethodException ex) {
 533             Error err = new NoSuchMethodError(ex.getMessage());
 534             throw initCauseFrom(err, ex);
 535         } catch (NoSuchFieldException ex) {
 536             Error err = new NoSuchFieldError(ex.getMessage());
 537             throw initCauseFrom(err, ex);
 538         } catch (ReflectiveOperationException ex) {
 539             Error err = new IncompatibleClassChangeError();
 540             throw initCauseFrom(err, ex);
 541         }
 542     }
 543 
 544     /**
 545      * Use best possible cause for err.initCause(), substituting the
 546      * cause for err itself if the cause has the same (or better) type.
 547      */
 548     private static Error initCauseFrom(Error err, Exception ex) {
 549         Throwable th = ex.getCause();
 550         if (err.getClass().isInstance(th))
 551            return (Error) th;
 552         err.initCause(th == null ? ex : th);
 553         return err;
 554     }
 555 
 556     /**
 557      * Is this method a caller-sensitive method?
 558      * I.e., does it call Reflection.getCallerClass or a similar method
 559      * to ask about the identity of its caller?
 560      */
 561     static boolean isCallerSensitive(MemberName mem) {
 562         if (!mem.isInvocable())  return false;  // fields are not caller sensitive
 563 
 564         return mem.isCallerSensitive() || canBeCalledVirtual(mem);
 565     }
 566 
 567     static boolean canBeCalledVirtual(MemberName mem) {
 568         assert(mem.isInvocable());
 569         Class<?> defc = mem.getDeclaringClass();
 570         switch (mem.getName()) {
 571         case "checkMemberAccess":
 572             return canBeCalledVirtual(mem, java.lang.SecurityManager.class);
 573         case "getContextClassLoader":
 574             return canBeCalledVirtual(mem, java.lang.Thread.class);
 575         }
 576         return false;
 577     }
 578 
 579     static boolean canBeCalledVirtual(MemberName symbolicRef, Class<?> definingClass) {
 580         Class<?> symbolicRefClass = symbolicRef.getDeclaringClass();
 581         if (symbolicRefClass == definingClass)  return true;
 582         if (symbolicRef.isStatic() || symbolicRef.isPrivate())  return false;
 583         return (definingClass.isAssignableFrom(symbolicRefClass) ||  // Msym overrides Mdef
 584                 symbolicRefClass.isInterface());                     // Mdef implements Msym
 585     }
 586 }