< prev index next >

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

Print this page




 108     @ForceInline // to ensure Reflection.getCallerClass optimization
 109     public static Lookup lookup() {
 110         return new Lookup(Reflection.getCallerClass());
 111     }
 112 
 113     /**
 114      * This reflected$lookup method is the alternate implementation of
 115      * the lookup method when being invoked by reflection.
 116      */
 117     @CallerSensitive
 118     private static Lookup reflected$lookup() {
 119         Class<?> caller = Reflection.getCallerClass();
 120         if (caller.getClassLoader() == null) {
 121             throw newIllegalArgumentException("illegal lookupClass: "+caller);
 122         }
 123         return new Lookup(caller);
 124     }
 125 
 126     /**
 127      * Returns a {@link Lookup lookup object} which is trusted minimally.
 128      * The lookup has the {@code PUBLIC} and {@code UNCONDITIONAL} modes.
 129      * It can only be used to create method handles to public members of
 130      * public classes in packages that are exported unconditionally.
 131      * <p>
 132      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 133      * of this lookup object will be {@link java.lang.Object}.
 134      *
 135      * @apiNote The use of Object is conventional, and because the lookup modes are
 136      * limited, there is no special access provided to the internals of Object, its package
 137      * or its module. Consequently, the lookup context of this lookup object will be the
 138      * bootstrap class loader, which means it cannot find user classes.

 139      *
 140      * <p style="font-size:smaller;">
 141      * <em>Discussion:</em>
 142      * The lookup class can be changed to any other class {@code C} using an expression of the form
 143      * {@link Lookup#in publicLookup().in(C.class)}.
 144      * but may change the lookup context by virtue of changing the class loader.
 145      * A public lookup object is always subject to
 146      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 147      * Also, it cannot access
 148      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 149      * @return a lookup object which is trusted minimally
 150      *
 151      * @revised 9
 152      * @spec JPMS
 153      */
 154     public static Lookup publicLookup() {
 155         return Lookup.PUBLIC_LOOKUP;
 156     }
 157 
 158     /**
 159      * Returns a {@link Lookup lookup object} with full capabilities to emulate all
 160      * supported bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc">
 161      * private access</a>, on a target class.
 162      * This method checks that a caller, specified as a {@code Lookup} object, is allowed to
 163      * do <em>deep reflection</em> on the target class. If {@code m1} is the module containing
 164      * the {@link Lookup#lookupClass() lookup class}, and {@code m2} is the module containing
 165      * the target class, then this check ensures that


 166      * <ul>
 167      *     <li>{@code m1} {@link Module#canRead reads} {@code m2}.</li>
 168      *     <li>{@code m2} {@link Module#isOpen(String,Module) opens} the package containing
 169      *     the target class to at least {@code m1}.</li>
 170      *     <li>The lookup has the {@link Lookup#MODULE MODULE} lookup mode.</li>




















 171      * </ul>
 172      * <p>
 173      * If there is a security manager, its {@code checkPermission} method is called to
 174      * check {@code ReflectPermission("suppressAccessChecks")}.
 175      * @apiNote The {@code MODULE} lookup mode serves to authenticate that the lookup object
 176      * was created by code in the caller module (or derived from a lookup object originally
 177      * created by the caller). A lookup object with the {@code MODULE} lookup mode can be
 178      * shared with trusted parties without giving away {@code PRIVATE} and {@code PACKAGE}
 179      * access to the caller.





 180      * @param targetClass the target class
 181      * @param lookup the caller lookup object
 182      * @return a lookup object for the target class, with private access
 183      * @throws IllegalArgumentException if {@code targetClass} is a primitve type or array class
 184      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}
 185      * @throws IllegalAccessException if the access check specified above fails
 186      * @throws SecurityException if denied by the security manager

 187      * @since 9
 188      * @spec JPMS
 189      * @see Lookup#dropLookupMode

 190      */
 191     public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {
 192         SecurityManager sm = System.getSecurityManager();
 193         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 194         if (targetClass.isPrimitive())
 195             throw new IllegalArgumentException(targetClass + " is a primitive class");
 196         if (targetClass.isArray())
 197             throw new IllegalArgumentException(targetClass + " is an array class");
 198         Module targetModule = targetClass.getModule();
 199         Module callerModule = lookup.lookupClass().getModule();














 200         if (!callerModule.canRead(targetModule))
 201             throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 202         if (targetModule.isNamed()) {
 203             String pn = targetClass.getPackageName();
 204             assert !pn.isEmpty() : "unnamed package cannot be in named module";
 205             if (!targetModule.isOpen(pn, callerModule))
 206                 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 207         }
 208         if ((lookup.lookupModes() & Lookup.MODULE) == 0)
 209             throw new IllegalAccessException("lookup does not have MODULE lookup mode");




 210         if (!callerModule.isNamed() && targetModule.isNamed()) {
 211             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
 212             if (logger != null) {
 213                 logger.logIfOpenedForIllegalAccess(lookup, targetClass);
 214             }
 215         }
 216         return new Lookup(targetClass);
 217     }
 218 
 219     /**
 220      * Performs an unchecked "crack" of a
 221      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 222      * The result is as if the user had obtained a lookup object capable enough
 223      * to crack the target method handle, called
 224      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 225      * on the target to obtain its symbolic reference, and then called
 226      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 227      * to resolve the symbolic reference to a member.
 228      * <p>
 229      * If there is a security manager, its {@code checkPermission} method
 230      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 231      * @param <T> the desired type of the result, either {@link Member} or a subtype
 232      * @param target a direct method handle to crack into symbolic reference components
 233      * @param expected a class object representing the desired result type {@code T}
 234      * @return a reference to the method, constructor, or field object
 235      * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
 236      * @exception NullPointerException if either argument is {@code null}


 516      * include the possibility of accessing {@code private} members
 517      * (which includes the private members of nestmates).
 518      * As documented in the relevant methods elsewhere,
 519      * only lookups with private access possess the following capabilities:
 520      * <ul style="font-size:smaller;">
 521      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 522      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 523      *     such as {@code Class.forName}
 524      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 525      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 526      *     for classes accessible to the lookup class
 527      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 528      *     within the same package member
 529      * </ul>
 530      * <p style="font-size:smaller;">
 531      * Each of these permissions is a consequence of the fact that a lookup object
 532      * with private access can be securely traced back to an originating class,
 533      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 534      * can be reliably determined and emulated by method handles.
 535      *




























































































































































































































































































































































































































































































































 536      * <h2><a id="secmgr"></a>Security manager interactions</h2>
 537      * Although bytecode instructions can only refer to classes in
 538      * a related class loader, this API can search for methods in any
 539      * class, as long as a reference to its {@code Class} object is
 540      * available.  Such cross-loader references are also possible with the
 541      * Core Reflection API, and are impossible to bytecode instructions
 542      * such as {@code invokestatic} or {@code getfield}.
 543      * There is a {@linkplain java.lang.SecurityManager security manager API}
 544      * to allow applications to check such cross-loader references.
 545      * These checks apply to both the {@code MethodHandles.Lookup} API
 546      * and the Core Reflection API
 547      * (as found on {@link java.lang.Class Class}).
 548      * <p>
 549      * If a security manager is present, member and class lookups are subject to
 550      * additional checks.
 551      * From one to three calls are made to the security manager.
 552      * Any of these calls can refuse access by throwing a
 553      * {@link java.lang.SecurityException SecurityException}.
 554      * Define {@code smgr} as the security manager,
 555      * {@code lookc} as the lookup class of the current lookup object,


 628      * If an application caches method handles for broad sharing,
 629      * it should use {@code publicLookup()} to create them.
 630      * If there is a lookup of {@code Class.forName}, it will fail,
 631      * and the application must take appropriate action in that case.
 632      * It may be that a later lookup, perhaps during the invocation of a
 633      * bootstrap method, can incorporate the specific identity
 634      * of the caller, making the method accessible.
 635      * <p style="font-size:smaller;">
 636      * The function {@code MethodHandles.lookup} is caller sensitive
 637      * so that there can be a secure foundation for lookups.
 638      * Nearly all other methods in the JSR 292 API rely on lookup
 639      * objects to check access requests.
 640      *
 641      * @revised 9
 642      */
 643     public static final
 644     class Lookup {
 645         /** The class on behalf of whom the lookup is being performed. */
 646         private final Class<?> lookupClass;
 647 



 648         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
 649         private final int allowedModes;
 650 
 651         static {
 652             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
 653         }
 654 
 655         /** A single-bit mask representing {@code public} access,
 656          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 657          *  The value, {@code 0x01}, happens to be the same as the value of the
 658          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.




 659          */
 660         public static final int PUBLIC = Modifier.PUBLIC;
 661 
 662         /** A single-bit mask representing {@code private} access,
 663          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 664          *  The value, {@code 0x02}, happens to be the same as the value of the
 665          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
 666          */
 667         public static final int PRIVATE = Modifier.PRIVATE;
 668 
 669         /** A single-bit mask representing {@code protected} access,
 670          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 671          *  The value, {@code 0x04}, happens to be the same as the value of the
 672          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
 673          */
 674         public static final int PROTECTED = Modifier.PROTECTED;
 675 
 676         /** A single-bit mask representing {@code package} access (default access),
 677          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 678          *  The value is {@code 0x08}, which does not correspond meaningfully to
 679          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 680          */
 681         public static final int PACKAGE = Modifier.STATIC;
 682 
 683         /** A single-bit mask representing {@code module} access (default access),
 684          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 685          *  The value is {@code 0x10}, which does not correspond meaningfully to
 686          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 687          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
 688          *  with this lookup mode can access all public types in the module of the
 689          *  lookup class and public types in packages exported by other modules
 690          *  to the module of the lookup class.




 691          *  @since 9
 692          *  @spec JPMS
 693          */
 694         public static final int MODULE = PACKAGE << 1;
 695 
 696         /** A single-bit mask representing {@code unconditional} access
 697          *  which may contribute to the result of {@link #lookupModes lookupModes}.
 698          *  The value is {@code 0x20}, which does not correspond meaningfully to
 699          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
 700          *  A {@code Lookup} with this lookup mode assumes {@linkplain
 701          *  java.lang.Module#canRead(java.lang.Module) readability}.
 702          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
 703          *  with this lookup mode can access all public members of public types
 704          *  of all modules where the type is in a package that is {@link
 705          *  java.lang.Module#isExported(String) exported unconditionally}.





 706          *  @since 9
 707          *  @spec JPMS
 708          *  @see #publicLookup()
 709          */
 710         public static final int UNCONDITIONAL = PACKAGE << 2;
 711 
 712         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL);
 713         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);
 714         private static final int TRUSTED   = -1;
 715 




 716         private static int fixmods(int mods) {
 717             mods &= (ALL_MODES - PACKAGE - MODULE - UNCONDITIONAL);
 718             return (mods != 0) ? mods : (PACKAGE | MODULE | UNCONDITIONAL);


 719         }
 720 
 721         /** Tells which class is performing the lookup.  It is this class against
 722          *  which checks are performed for visibility and access permissions.
 723          *  <p>



 724          *  The class implies a maximum level of access permission,
 725          *  but the permissions may be additionally limited by the bitmask
 726          *  {@link #lookupModes lookupModes}, which controls whether non-public members
 727          *  can be accessed.
 728          *  @return the lookup class, on behalf of which this lookup object finds members

 729          */
 730         public Class<?> lookupClass() {
 731             return lookupClass;
 732         }
 733 





















 734         // This is just for calling out to MethodHandleImpl.
 735         private Class<?> lookupClassOrNull() {
 736             return (allowedModes == TRUSTED) ? null : lookupClass;
 737         }
 738 
 739         /** Tells which access-protection classes of members this lookup object can produce.
 740          *  The result is a bit-mask of the bits
 741          *  {@linkplain #PUBLIC PUBLIC (0x01)},
 742          *  {@linkplain #PRIVATE PRIVATE (0x02)},
 743          *  {@linkplain #PROTECTED PROTECTED (0x04)},
 744          *  {@linkplain #PACKAGE PACKAGE (0x08)},
 745          *  {@linkplain #MODULE MODULE (0x10)},
 746          *  and {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}.
 747          *  <p>
 748          *  A freshly-created lookup object
 749          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
 750          *  all possible bits set, except {@code UNCONDITIONAL}.
 751          *  A lookup object on a new lookup class
 752          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
 753          *  may have some mode bits set to zero.


 757          *  The purpose of this is to restrict access via the new lookup object,
 758          *  so that it can access only names which can be reached by the original
 759          *  lookup object, and also by the new lookup class.
 760          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
 761          *  @see #in
 762          *  @see #dropLookupMode
 763          *
 764          *  @revised 9
 765          *  @spec JPMS
 766          */
 767         public int lookupModes() {
 768             return allowedModes & ALL_MODES;
 769         }
 770 
 771         /** Embody the current class (the lookupClass) as a lookup class
 772          * for method handle creation.
 773          * Must be called by from a method in this package,
 774          * which in turn is called by a method not in this package.
 775          */
 776         Lookup(Class<?> lookupClass) {
 777             this(lookupClass, FULL_POWER_MODES);
 778             // make sure we haven't accidentally picked up a privileged class:
 779             checkUnprivilegedlookupClass(lookupClass);
 780         }
 781 
 782         private Lookup(Class<?> lookupClass, int allowedModes) {



 783             this.lookupClass = lookupClass;

 784             this.allowedModes = allowedModes;
 785         }
 786 






 787         /**
 788          * Creates a lookup on the specified new lookup class.
 789          * The resulting object will report the specified
 790          * class as its own {@link #lookupClass() lookupClass}.

 791          * <p>
 792          * However, the resulting {@code Lookup} object is guaranteed
 793          * to have no more access capabilities than the original.
 794          * In particular, access capabilities can be lost as follows:<ul>
 795          * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
 796          * the new lookup class is in a different module {@code M}, then no members, not
 797          * even public members in {@code M}'s exported packages, will be accessible.
 798          * The exception to this is when this lookup is {@link #publicLookup()
 799          * publicLookup}, in which case {@code PUBLIC} access is not lost.
 800          * <li>If the old lookup class is in an unnamed module, and the new lookup class
 801          * is a different module then {@link #MODULE MODULE} access is lost.
 802          * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
 803          * <li>If the new lookup class is in a different package
 804          * than the old one, protected and default (package) members will not be accessible.

 805          * <li>If the new lookup class is not within the same package member
 806          * as the old one, private members will not be accessible, and protected members
 807          * will not be accessible by virtue of inheritance.

 808          * (Protected members may continue to be accessible because of package sharing.)
 809          * <li>If the new lookup class is not accessible to the old lookup class,
 810          * then no members, not even public members, will be accessible.
 811          * (In all other cases, public members will continue to be accessible.)




 812          * </ul>
 813          * <p>










 814          * The resulting lookup's capabilities for loading classes
 815          * (used during {@link #findClass} invocations)
 816          * are determined by the lookup class' loader,
 817          * which may change due to this operation.
 818          *
 819          * @param requestedLookupClass the desired lookup class for the new lookup object
 820          * @return a lookup object which reports the desired lookup class, or the same object
 821          * if there is no change
 822          * @throws NullPointerException if the argument is null
 823          *
 824          * @revised 9
 825          * @spec JPMS


 826          */
 827         public Lookup in(Class<?> requestedLookupClass) {
 828             Objects.requireNonNull(requestedLookupClass);
 829             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
 830                 return new Lookup(requestedLookupClass, FULL_POWER_MODES);
 831             if (requestedLookupClass == this.lookupClass)
 832                 return this;  // keep same capabilities
 833             int newModes = (allowedModes & FULL_POWER_MODES);
 834             if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
 835                 // Need to drop all access when teleporting from a named module to another
 836                 // module. The exception is publicLookup where PUBLIC is not lost.
 837                 if (this.lookupClass.getModule().isNamed()
 838                     && (this.allowedModes & UNCONDITIONAL) == 0)





 839                     newModes = 0;
 840                 else

 841                     newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);


 842             }
 843             if ((newModes & PACKAGE) != 0
 844                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
 845                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
 846             }
 847             // Allow nestmate lookups to be created without special privilege:
 848             if ((newModes & PRIVATE) != 0
 849                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
 850                 newModes &= ~(PRIVATE|PROTECTED);
 851             }
 852             if ((newModes & PUBLIC) != 0
 853                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
 854                 // The requested class it not accessible from the lookup class.
 855                 // No permissions.
 856                 newModes = 0;
 857             }
 858 
 859             checkUnprivilegedlookupClass(requestedLookupClass);
 860             return new Lookup(requestedLookupClass, newModes);
 861         }
 862 
 863 
 864         /**
 865          * Creates a lookup on the same lookup class which this lookup object
 866          * finds members, but with a lookup mode that has lost the given lookup mode.
 867          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
 868          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}.
 869          * {@link #PROTECTED PROTECTED} and {@link #UNCONDITIONAL UNCONDITIONAL} are always
 870          * dropped and so the resulting lookup mode will never have these access capabilities.
 871          * When dropping {@code PACKAGE} then the resulting lookup will not have {@code PACKAGE}
 872          * or {@code PRIVATE} access. When dropping {@code MODULE} then the resulting lookup will
 873          * not have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code PUBLIC}

 874          * is dropped then the resulting lookup has no access.












 875          * @param modeToDrop the lookup mode to drop
 876          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
 877          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
 878          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE} or {@code UNCONDITIONAL}
 879          * @see MethodHandles#privateLookupIn
 880          * @since 9
 881          */
 882         public Lookup dropLookupMode(int modeToDrop) {
 883             int oldModes = lookupModes();
 884             int newModes = oldModes & ~(modeToDrop | PROTECTED | UNCONDITIONAL);
 885             switch (modeToDrop) {
 886                 case PUBLIC: newModes &= ~(ALL_MODES); break;
 887                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
 888                 case PACKAGE: newModes &= ~(PRIVATE); break;
 889                 case PROTECTED:
 890                 case PRIVATE:
 891                 case UNCONDITIONAL: break;
 892                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
 893             }
 894             if (newModes == oldModes) return this;  // return self if no change
 895             return new Lookup(lookupClass(), newModes);
 896         }
 897 
 898         /**
 899          * Defines a class to the same class loader and in the same runtime package and
 900          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
 901          * {@linkplain #lookupClass() lookup class}.
 902          *
 903          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
 904          * {@link #PACKAGE PACKAGE} access as default (package) members will be
 905          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
 906          * that the lookup object was created by a caller in the runtime package (or derived
 907          * from a lookup originally created by suitably privileged code to a target class in
 908          * the runtime package). </p>
 909          *
 910          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
 911          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
 912          * same package as the lookup class. </p>
 913          *
 914          * <p> This method does not run the class initializer. The class initializer may
 915          * run at a later time, as detailed in section 12.4 of the <em>The Java Language


 980             ProtectionDomain pd = cachedProtectionDomain;
 981             if (pd == null) {
 982                 cachedProtectionDomain = pd = protectionDomain(lookupClass);
 983             }
 984             return pd;
 985         }
 986 
 987         private ProtectionDomain protectionDomain(Class<?> clazz) {
 988             PrivilegedAction<ProtectionDomain> pa = clazz::getProtectionDomain;
 989             return AccessController.doPrivileged(pa);
 990         }
 991 
 992         // cached protection domain
 993         private volatile ProtectionDomain cachedProtectionDomain;
 994 
 995 
 996         // Make sure outer class is initialized first.
 997         static { IMPL_NAMES.getClass(); }
 998 
 999         /** Package-private version of lookup which is trusted. */
1000         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
1001 
1002         /** Version of lookup which is trusted minimally.
1003          *  It can only be used to create method handles to publicly accessible
1004          *  members in packages that are exported unconditionally.
1005          */
1006         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, (PUBLIC|UNCONDITIONAL));
1007 
1008         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1009             String name = lookupClass.getName();
1010             if (name.startsWith("java.lang.invoke."))
1011                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1012         }
1013 
1014         /**
1015          * Displays the name of the class from which lookups are to be made.


1016          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1017          * If there are restrictions on the access permitted to this lookup,
1018          * this is indicated by adding a suffix to the class name, consisting
1019          * of a slash and a keyword.  The keyword represents the strongest
1020          * allowed access, and is chosen as follows:
1021          * <ul>
1022          * <li>If no access is allowed, the suffix is "/noaccess".

1023          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
1024          * <li>If only public access and unconditional access are allowed, the suffix is "/publicLookup".
1025          * <li>If only public and module access are allowed, the suffix is "/module".
1026          * <li>If only public, module and package access are allowed, the suffix is "/package".
1027          * <li>If only public, module, package, and private access are allowed, the suffix is "/private".
1028          * </ul>
1029          * If none of the above cases apply, it is the case that full
1030          * access (public, module, package, private, and protected) is allowed.
1031          * In this case, no suffix is added.
1032          * This is true only of an object obtained originally from
1033          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
1034          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
1035          * always have restricted access, and will display a suffix.
1036          * <p>
1037          * (It may seem strange that protected access should be
1038          * stronger than private access.  Viewed independently from
1039          * package access, protected access is the first to be lost,
1040          * because it requires a direct subclass relationship between
1041          * caller and callee.)
1042          * @see #in
1043          *
1044          * @revised 9
1045          * @spec JPMS
1046          */
1047         @Override
1048         public String toString() {
1049             String cname = lookupClass.getName();


1050             switch (allowedModes) {
1051             case 0:  // no privileges
1052                 return cname + "/noaccess";


1053             case PUBLIC:
1054                 return cname + "/public";
1055             case PUBLIC|UNCONDITIONAL:
1056                 return cname  + "/publicLookup";
1057             case PUBLIC|MODULE:
1058                 return cname + "/module";

1059             case PUBLIC|MODULE|PACKAGE:
1060                 return cname + "/package";
1061             case FULL_POWER_MODES & ~PROTECTED:

1062                 return cname + "/private";
1063             case FULL_POWER_MODES:

1064                 return cname;
1065             case TRUSTED:
1066                 return "/trusted";  // internal only; not exported
1067             default:  // Should not happen, but it's a bitfield...
1068                 cname = cname + "/" + Integer.toHexString(allowedModes);
1069                 assert(false) : cname;
1070                 return cname;
1071             }
1072         }
1073 
1074         /**
1075          * Produces a method handle for a static method.
1076          * The type of the method handle will be that of the method.
1077          * (Since static methods do not take receivers, there is no
1078          * additional receiver argument inserted into the method handle type,
1079          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
1080          * The method and all its argument types must be accessible to the lookup object.
1081          * <p>
1082          * The returned method handle will have
1083          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if


1284          * load the requested class, and then determines whether the class is accessible to this lookup object.
1285          *
1286          * @param targetName the fully qualified name of the class to be looked up.
1287          * @return the requested class.
1288          * @exception SecurityException if a security manager is present and it
1289          *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1290          * @throws LinkageError if the linkage fails
1291          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
1292          * @throws IllegalAccessException if the class is not accessible, using the allowed access
1293          * modes.
1294          * @exception SecurityException if a security manager is present and it
1295          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1296          * @since 9
1297          */
1298         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1299             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1300             return accessClass(targetClass);
1301         }
1302 
1303         /**
1304          * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The
1305          * static initializer of the class is not run.
1306          * <p>
1307          * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the
1308          * {@linkplain #lookupModes() lookup modes}.















1309          *
1310          * @param targetClass the class to be access-checked



































1311          *

1312          * @return the class that has been access-checked
1313          *
1314          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
1315          * modes.
1316          * @exception SecurityException if a security manager is present and it
1317          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1318          * @since 9

1319          */
1320         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
1321             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) {
1322                 throw new MemberName(targetClass).makeAccessException("access violation", this);
1323             }
1324             checkSecurityManager(targetClass, null);
1325             return targetClass;
1326         }
1327 
1328         /**
1329          * Produces an early-bound method handle for a virtual method.
1330          * It will bypass checks for overriding methods on the receiver,
1331          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
1332          * instruction from within the explicitly specified {@code specialCaller}.
1333          * The type of the method handle will be that of the method,
1334          * with a suitably restricted receiver type prepended.
1335          * (The receiver type will be {@code specialCaller} or a subtype.)
1336          * The method and all its argument types must be accessible
1337          * to the lookup object.
1338          * <p>
1339          * Before method resolution,
1340          * if the explicitly specified caller class is not identical with the
1341          * lookup class, or if this lookup object does not have


2066 
2067         MemberName resolveOrNull(byte refKind, MemberName member) {
2068             // do this before attempting to resolve
2069             if (!isClassAccessible(member.getDeclaringClass())) {
2070                 return null;
2071             }
2072             Objects.requireNonNull(member.getName());
2073             Objects.requireNonNull(member.getType());
2074             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull());
2075         }
2076 
2077         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
2078             if (!isClassAccessible(refc)) {
2079                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
2080             }
2081         }
2082 
2083         boolean isClassAccessible(Class<?> refc) {
2084             Objects.requireNonNull(refc);
2085             Class<?> caller = lookupClassOrNull();
2086             return caller == null || VerifyAccess.isClassAccessible(refc, caller, allowedModes);
2087         }
2088 
2089         /** Check name for an illegal leading "&lt;" character. */
2090         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
2091             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
2092                 throw new NoSuchMethodException("illegal method name: "+name);
2093         }
2094 
2095 
2096         /**
2097          * Find my trustable caller class if m is a caller sensitive method.
2098          * If this lookup object has private access, then the caller class is the lookupClass.
2099          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
2100          */
2101         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
2102             Class<?> callerClass = null;
2103             if (MethodHandleNatives.isCallerSensitive(m)) {
2104                 // Only lookups with private access are allowed to resolve caller-sensitive methods
2105                 if (hasPrivateAccess()) {
2106                     callerClass = lookupClass;


2203                 // All arrays simply inherit Object.clone.
2204                 // But for access checking logic, we make Object.clone
2205                 // (normally protected) appear to be public.
2206                 // Later on, when the DirectMethodHandle is created,
2207                 // its leading argument will be restricted to the
2208                 // requested array type.
2209                 // N.B. The return type is not adjusted, because
2210                 // that is *not* the bytecode behavior.
2211                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
2212             }
2213             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
2214                 // cannot "new" a protected ctor in a different package
2215                 mods ^= Modifier.PROTECTED;
2216             }
2217             if (Modifier.isFinal(mods) &&
2218                     MethodHandleNatives.refKindIsSetter(refKind))
2219                 throw m.makeAccessException("unexpected set of a final field", this);
2220             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
2221             if ((requestedModes & allowedModes) != 0) {
2222                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
2223                                                     mods, lookupClass(), allowedModes))
2224                     return;
2225             } else {
2226                 // Protected members can also be checked as if they were package-private.
2227                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
2228                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
2229                     return;
2230             }
2231             throw m.makeAccessException(accessFailedMessage(refc, m), this);
2232         }
2233 
2234         String accessFailedMessage(Class<?> refc, MemberName m) {
2235             Class<?> defc = m.getDeclaringClass();
2236             int mods = m.getModifiers();
2237             // check the class first:
2238             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
2239                                (defc == refc ||
2240                                 Modifier.isPublic(refc.getModifiers())));
2241             if (!classOK && (allowedModes & PACKAGE) != 0) {
2242                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), FULL_POWER_MODES) &&

2243                            (defc == refc ||
2244                             VerifyAccess.isClassAccessible(refc, lookupClass(), FULL_POWER_MODES)));
2245             }
2246             if (!classOK)
2247                 return "class is not public";
2248             if (Modifier.isPublic(mods))
2249                 return "access to public member failed";  // (how?, module not readable?)
2250             if (Modifier.isPrivate(mods))
2251                 return "member is private";
2252             if (Modifier.isProtected(mods))
2253                 return "member is protected";
2254             return "member is private to package";
2255         }
2256 
2257         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
2258             int allowedModes = this.allowedModes;
2259             if (allowedModes == TRUSTED)  return;
2260             if (!hasPrivateAccess()
2261                 || (specialCaller != lookupClass()
2262                        // ensure non-abstract methods in superinterfaces can be special-invoked
2263                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
2264                 throw new MemberName(specialCaller).




 108     @ForceInline // to ensure Reflection.getCallerClass optimization
 109     public static Lookup lookup() {
 110         return new Lookup(Reflection.getCallerClass());
 111     }
 112 
 113     /**
 114      * This reflected$lookup method is the alternate implementation of
 115      * the lookup method when being invoked by reflection.
 116      */
 117     @CallerSensitive
 118     private static Lookup reflected$lookup() {
 119         Class<?> caller = Reflection.getCallerClass();
 120         if (caller.getClassLoader() == null) {
 121             throw newIllegalArgumentException("illegal lookupClass: "+caller);
 122         }
 123         return new Lookup(caller);
 124     }
 125 
 126     /**
 127      * Returns a {@link Lookup lookup object} which is trusted minimally.
 128      * The lookup has the {@code UNCONDITIONAL} mode.
 129      * It can only be used to create method handles to public members of
 130      * public classes in packages that are exported unconditionally.
 131      * <p>
 132      * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
 133      * of this lookup object will be {@link java.lang.Object}.
 134      *
 135      * @apiNote The use of Object is conventional, and because the lookup modes are
 136      * limited, there is no special access provided to the internals of Object, its package
 137      * or its module.  This public lookup object or other lookup object with
 138      * {@code UNCONDITIONAL} mode assumes readability. Consequently, the lookup class
 139      * is not used to determine the lookup context.
 140      *
 141      * <p style="font-size:smaller;">
 142      * <em>Discussion:</em>
 143      * The lookup class can be changed to any other class {@code C} using an expression of the form
 144      * {@link Lookup#in publicLookup().in(C.class)}.

 145      * A public lookup object is always subject to
 146      * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
 147      * Also, it cannot access
 148      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
 149      * @return a lookup object which is trusted minimally
 150      *
 151      * @revised 9
 152      * @spec JPMS
 153      */
 154     public static Lookup publicLookup() {
 155         return Lookup.PUBLIC_LOOKUP;
 156     }
 157 
 158     /**
 159      * Returns a {@link Lookup lookup} object on a target class to emulate all supported
 160      * bytecode behaviors, including <a href="MethodHandles.Lookup.html#privacc"> private access</a>.
 161      * The returned lookup object can provide access to classes in modules and packages,
 162      * and members of those classes, outside the normal rules of Java access control,
 163      * instead conforming to the more permissive rules for modular <em>deep reflection</em>.
 164      * <p>
 165      * A caller, specified as a {@code Lookup} object, is in module {@code M1} is
 166      * allowed to do deep reflection on module {@code M2} and package of the target class
 167      * if and only if all of the following conditions are {@code true}:
 168      * <ul>
 169      * <li>If there is a security manager, its {@code checkPermission} method is
 170      * called to check {@code ReflectPermission("suppressAccessChecks")} and
 171      * that must return normally.
 172      * <li>
 173      * If there is a security manager, its {@code checkPermission} method is
 174      * called to check {@code ReflectPermission("suppressAccessChecks")}.
 175      * This method must return normally.
 176      * <li>The caller lookup object must have the {@link Lookup#MODULE MODULE} lookup mode.
 177      * (This is because otherwise there would be no way to ensure the original lookup
 178      * creator was a member of any particular module, and so any subsequent checks
 179      * for readability and qualified exports would become ineffective.)
 180      * <li>The caller lookup object must have {@link Lookup#PRIVATE PRIVATE} access.
 181      * (This is because an application intending to share intra-module access
 182      * using {@link Lookup#MODULE MODULE} alone will inadvertently also share
 183      * deep reflection to its own module.)
 184      * <li>The target class must be a proper class, not a primitive or array class.
 185      * (Thus, {@code M2} is well-defined.)
 186      * <li>If the caller module {@code M1} differs from
 187      * the target module {@code M2} then both of the following must be true:
 188      *   <ul>
 189      *     <li>{@code M1} {@link Module#canRead reads} {@code M2}.</li>
 190      *     <li>{@code M2} {@link Module#isOpen(String,Module) opens} the package
 191      *         containing the target class to at least {@code M1}.</li>
 192      *   </ul>
 193      * </ul>
 194      * <p>
 195      * If any of the above checks is violated, this method fails with an
 196      * exception.
 197      * <p>
 198      * Otherwise, if {@code M1} and {@code M2} are the same module, this method
 199      * returns a {@code Lookup} on {@code targetClass} with full capabilities and
 200      * {@code null} previous lookup class.
 201      * <p>
 202      * Otherwise, {@code M1} and {@code M2} are two different modules.  This method
 203      * returns a {@code Lookup} on {@code targetClass} that records
 204      * the lookup class of the caller as the new previous lookup class and
 205      * drops {@code MODULE} access from the full capabilities mode.
 206      *
 207      * @param targetClass the target class
 208      * @param caller the caller lookup object
 209      * @return a lookup object for the target class, with private access
 210      * @throws IllegalArgumentException if {@code targetClass} is a primitive type or array class
 211      * @throws NullPointerException if {@code targetClass} or {@code caller} is {@code null}

 212      * @throws SecurityException if denied by the security manager
 213      * @throws IllegalAccessException if any of the other access checks specified above fails
 214      * @since 9
 215      * @spec JPMS
 216      * @see Lookup#dropLookupMode
 217      * @see <a href="MethodHandles.Lookup.html#cross-module-lookup">Cross-module lookups</a>
 218      */
 219     public static Lookup privateLookupIn(Class<?> targetClass, Lookup caller) throws IllegalAccessException {
 220         SecurityManager sm = System.getSecurityManager();
 221         if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
 222         if (targetClass.isPrimitive())
 223             throw new IllegalArgumentException(targetClass + " is a primitive class");
 224         if (targetClass.isArray())
 225             throw new IllegalArgumentException(targetClass + " is an array class");
 226         // Ensure that we can reason accurately about private and module access.
 227         if ((caller.lookupModes() & Lookup.PRIVATE) == 0)
 228             throw new IllegalAccessException("caller does not have PRIVATE lookup mode");
 229         if ((caller.lookupModes() & Lookup.MODULE) == 0)
 230             throw new IllegalAccessException("caller does not have MODULE lookup mode");
 231 
 232         // previous lookup class is never set if it has MODULE access
 233         assert caller.previousLookupClass() == null;
 234 
 235         Class<?> callerClass = caller.lookupClass();
 236         Module callerModule = callerClass.getModule();  // M1
 237         Module targetModule = targetClass.getModule();  // M2
 238         Class<?> newPreviousClass = null;
 239         int newModes = Lookup.FULL_POWER_MODES;
 240 
 241         if (targetModule != callerModule) {
 242             if (!callerModule.canRead(targetModule))
 243                 throw new IllegalAccessException(callerModule + " does not read " + targetModule);
 244             if (targetModule.isNamed()) {
 245                 String pn = targetClass.getPackageName();
 246                 assert !pn.isEmpty() : "unnamed package cannot be in named module";
 247                 if (!targetModule.isOpen(pn, callerModule))
 248                     throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
 249             }
 250 
 251             // M2 != M1, set previous lookup class to M1 and drop MODULE access
 252             newPreviousClass = callerClass;
 253             newModes &= ~Lookup.MODULE;
 254         }
 255 
 256         if (!callerModule.isNamed() && targetModule.isNamed()) {
 257             IllegalAccessLogger logger = IllegalAccessLogger.illegalAccessLogger();
 258             if (logger != null) {
 259                 logger.logIfOpenedForIllegalAccess(caller, targetClass);
 260             }
 261         }
 262         return Lookup.newLookup(targetClass, newPreviousClass, newModes);
 263     }
 264 
 265     /**
 266      * Performs an unchecked "crack" of a
 267      * <a href="MethodHandleInfo.html#directmh">direct method handle</a>.
 268      * The result is as if the user had obtained a lookup object capable enough
 269      * to crack the target method handle, called
 270      * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect}
 271      * on the target to obtain its symbolic reference, and then called
 272      * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs}
 273      * to resolve the symbolic reference to a member.
 274      * <p>
 275      * If there is a security manager, its {@code checkPermission} method
 276      * is called with a {@code ReflectPermission("suppressAccessChecks")} permission.
 277      * @param <T> the desired type of the result, either {@link Member} or a subtype
 278      * @param target a direct method handle to crack into symbolic reference components
 279      * @param expected a class object representing the desired result type {@code T}
 280      * @return a reference to the method, constructor, or field object
 281      * @exception SecurityException if the caller is not privileged to call {@code setAccessible}
 282      * @exception NullPointerException if either argument is {@code null}


 562      * include the possibility of accessing {@code private} members
 563      * (which includes the private members of nestmates).
 564      * As documented in the relevant methods elsewhere,
 565      * only lookups with private access possess the following capabilities:
 566      * <ul style="font-size:smaller;">
 567      * <li>access private fields, methods, and constructors of the lookup class and its nestmates
 568      * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods,
 569      *     such as {@code Class.forName}
 570      * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions
 571      * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a>
 572      *     for classes accessible to the lookup class
 573      * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes
 574      *     within the same package member
 575      * </ul>
 576      * <p style="font-size:smaller;">
 577      * Each of these permissions is a consequence of the fact that a lookup object
 578      * with private access can be securely traced back to an originating class,
 579      * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions
 580      * can be reliably determined and emulated by method handles.
 581      *
 582      * <h1><a id="cross-module-lookup"></a>Cross-module lookups</h1>
 583      * When a lookup class in one module {@code M1} accesses a class in another module
 584      * {@code M2}, extra access checking is performed beyond the access mode bits.
 585      * A {@code Lookup} with {@link #PUBLIC} mode and a lookup class in {@code M1}
 586      * can access public types in a module {@code M2} when {@code M2} is readable to
 587      * {@code M1} when the type is in a package of {@code M2} that is exported to
 588      * at least {@code M1}.
 589      * <p>
 590      * A {@code Lookup} on {@code C} can also <em>teleport</em> to a target class
 591      * via {@link #in(Class) Lookup.in} and {@link MethodHandles#privateLookupIn(Class, Lookup)
 592      * MethodHandles.privateLookupIn} methods.
 593      * Teleporting across modules will always record the original lookup class as
 594      * the <em>{@linkplain #previousLookupClass() previous lookup class}</em>
 595      * and drops {@link Lookup#MODULE MODULE} access.
 596      * If the target class is in the same module as the lookup class {@code C},
 597      * then the target class becomes the new lookup class
 598      * and there is no change to the previous lookup class.
 599      * If the target class is in a different module from {@code M1} ({@code C}'s module),
 600      * {@code C} becomes the new previous lookup class
 601      * and the target class becomes the new lookup class.
 602      * In that case, if there was already a previous lookup class in {@code M0},
 603      * and it differs from {@code M1} and {@code M2}, then the resulting lookup
 604      * drops all privileges.
 605      * For example,
 606      * <blockquote><pre>
 607      * {@code
 608      * Lookup lookup = MethodHandles.lookup();   // in class C
 609      * Lookup lookup2 = lookup.in(D.class);
 610      * MethodHandle mh = lookup2.findStatic(E.class, "m", MT);
 611      * }</pre></blockquote>
 612      * <p>
 613      * The {@link #lookup()} factory method produces a {@code Lookup} object
 614      * with {@code null} previous lookup class.
 615      * {@link Lookup#in lookup.in(D.class)} transforms the {@code lookup} on class {@code C}
 616      * to class {@code D} without elevation of privileges.
 617      * If {@code C} and {@code D} are in the same module,
 618      * {@code lookup2} records {@code D} as the new lookup class and keeps the
 619      * same previous lookup class as the original {@code lookup}, or
 620      * {@code null} if not present.
 621      * <p>
 622      * When a {@code Lookup} teleports from a class
 623      * in one nest to another nest, {@code PRIVATE} access is dropped.
 624      * When a {@code Lookup} teleports from a class in one package to
 625      * another package, {@code PACKAGE} access is dropped.
 626      * When a {@code Lookup} teleports from a class in one module to another module,
 627      * {@code MODULE} access is dropped.
 628      * Teleporting across modules drops the ability to access non-exported classes
 629      * in both the module of the new lookup class and the module of the old lookup class
 630      * and the resulting {@code Lookup} remains only {@code PUBLIC} access.
 631      * A {@code Lookup} can teleport back and forth to a class in the module of
 632      * the lookup class and the module of the previous class lookup.
 633      * Teleporting across modules can only decrease access but cannot increase it.
 634      * Teleporting to some third module drops all accesses.
 635      * <p>
 636      * In the above example, if {@code C} and {@code D} are in different modules,
 637      * {@code lookup2} records {@code D} as its lookup class and
 638      * {@code C} as its previous lookup class and {@code lookup2} has only
 639      * {@code PUBLIC} access. {@code lookup2} can teleport to other class in
 640      * {@code C}'s module and {@code D}'s module.
 641      * If class {@code E} is in a third module, {@code lookup2.in(E.class)} creates
 642      * a {@code Lookup} on {@code E} with no access and {@code lookup2}'s lookup
 643      * class {@code D} is recorded as its previous lookup class.
 644      * <p>
 645      * Teleporting across modules restricts access to the public types that
 646      * both the lookup class and the previous lookup class can equally access
 647      * (see below).
 648      * <p>
 649      * {@link MethodHandles#privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn(T.class, lookup)}
 650      * can be used to teleport a {@code lookup} from class {@code C} to class {@code T}
 651      * and create a new {@code Lookup} with <a href="#privcc">private access</a>
 652      * if the lookup class is allowed to do <em>deep reflection</em> on {@code T}.
 653      * The {@code lookup} must have {@link #MODULE} and {@link #PRIVATE} access
 654      * to call {@code privateLookupIn}.
 655      * A {@code lookup} on {@code C} in module {@code M1} is allowed to do deep reflection
 656      * on all classes in {@code M1}.  If {@code T} is in {@code M1}, {@code privateLookupIn}
 657      * produces a new {@code Lookup} on {@code T} with full capabilities.
 658      * A {@code lookup} on {@code C} is also allowed
 659      * to do deep reflection on {@code T} in another module {@code M2} if
 660      * {@code M1} reads {@code M2} and {@code M2} {@link Module#isOpen(String,Module) opens}
 661      * the package containing {@code T} to at least {@code M1}.
 662      * {@code T} becomes the new lookup class and {@code C} becomes the new previous
 663      * lookup class and {@code MODULE} access is dropped from the resulting {@code Lookup}.
 664      * The resulting {@code Lookup} can be used to do member lookup or teleport
 665      * to another lookup class by calling {@link #in Lookup::in}.  But
 666      * it cannot be used to obtain another private {@code Lookup} by calling
 667      * {@link MethodHandles#privateLookupIn(Class, Lookup) privateLookupIn}
 668      * because it has no {@code MODULE} access.
 669      *
 670      * <h1><a id="module-access-check"></a>Cross-module access checks</h1>
 671      *
 672      * A {@code Lookup} with {@link #PUBLIC} or with {@link #UNCONDITIONAL} mode
 673      * allows cross-module access. The access checking is performed with respect
 674      * to both the lookup class and the previous lookup class if present.
 675      * <p>
 676      * A {@code Lookup} with {@link #UNCONDITIONAL} mode can access public type
 677      * in all modules when the type is in a package that is {@linkplain Module#isExported(String)
 678      * exported unconditionally}.
 679      * <p>
 680      * If a {@code Lookup} on {@code LC} in {@code M1} has no previous lookup class,
 681      * the lookup with {@link #PUBLIC} mode can access all public types in modules
 682      * that are readable to {@code M1} and the type is in a package that is exported
 683      * at least to {@code M1}.
 684      * <p>
 685      * If a {@code Lookup} on {@code LC} in {@code M1} has a previous lookup class
 686      * {@code PLC} on {@code M0}, the lookup with {@link #PUBLIC} mode can access
 687      * the intersection of all public types that are accessible to {@code M1}
 688      * with all public types that are accessible to {@code M0}. {@code M0}
 689      * reads {@code M1} and hence the set of accessible types includes:
 690      *
 691      * <table class="striped">
 692      * <caption style="display:none">
 693      * Public types in the following packages are accessible to the
 694      * lookup class and the previous lookup class.
 695      * </caption>
 696      * <thead>
 697      * <tr>
 698      * <th scope="col">Equally accessible types to {@code M0} and {@code M1}</th>
 699      * </tr>
 700      * </thead>
 701      * <tbody>
 702      * <tr>
 703      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M1}</th>
 704      * </tr>
 705      * <tr>
 706      * <th scope="row" style="text-align:left">unconditional-exported packages from {@code M0} if {@code M1} reads {@code M0}</th>
 707      * </tr>
 708      * <tr>
 709      * <th scope="row" style="text-align:left">unconditional-exported packages from a third module {@code M2}
 710      * if both {@code M0} and {@code M1} read {@code M2}</th>
 711      * </tr>
 712      * <tr>
 713      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M1} to {@code M0}</th>
 714      * </tr>
 715      * <tr>
 716      * <th scope="row" style="text-align:left">qualified-exported packages from {@code M0} to {@code M1}
 717      * if {@code M1} reads {@code M0}</th>
 718      * </tr>
 719      * <tr>
 720      * <th scope="row" style="text-align:left">qualified-exported packages from a third module {@code M2} to
 721      * both {@code M0} and {@code M1} if both {@code M0} and {@code M1} read {@code M2}</th>
 722      * </tr>
 723      * </tbody>
 724      * </table>
 725      *
 726      * <h1><a id="access-modes"></a>Access modes</h1>
 727      *
 728      * The table below shows the access modes of a {@code Lookup} produced by
 729      * any of the following factory or transformation methods:
 730      * <ul>
 731      * <li>{@link #lookup() MethodHandles.lookup()}</li>
 732      * <li>{@link #publicLookup() MethodHandles.publicLookup()}</li>
 733      * <li>{@link #privateLookupIn(Class, Lookup) MethodHandles.privateLookupIn}</li>
 734      * <li>{@link Lookup#in}</li>
 735      * <li>{@link Lookup#dropLookupMode(int)}</li>
 736      * </ul>
 737      *
 738      * <table class="striped">
 739      * <caption style="display:none">
 740      * Access mode summary
 741      * </caption>
 742      * <thead>
 743      * <tr>
 744      * <th scope="col">Lookup object</th>
 745      * <th style="text-align:center">protected</th>
 746      * <th style="text-align:center">private</th>
 747      * <th style="text-align:center">package</th>
 748      * <th style="text-align:center">module</th>
 749      * <th style="text-align:center">public</th>
 750      * </tr>
 751      * </thead>
 752      * <tbody>
 753      * <tr>
 754      * <th scope="row" style="text-align:left">{@code CL = MethodHandles.lookup()} in {@code C}</th>
 755      * <td style="text-align:center">PRO</td>
 756      * <td style="text-align:center">PRI</td>
 757      * <td style="text-align:center">PAC</td>
 758      * <td style="text-align:center">MOD</td>
 759      * <td style="text-align:center">1R</td>
 760      * </tr>
 761      * <tr>
 762      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same package</th>
 763      * <td></td>
 764      * <td></td>
 765      * <td style="text-align:center">PAC</td>
 766      * <td style="text-align:center">MOD</td>
 767      * <td style="text-align:center">1R</td>
 768      * </tr>
 769      * <tr>
 770      * <th scope="row" style="text-align:left">{@code CL.in(C1)} same module</th>
 771      * <td></td>
 772      * <td></td>
 773      * <td></td>
 774      * <td style="text-align:center">MOD</td>
 775      * <td style="text-align:center">1R</td>
 776      * </tr>
 777      * <tr>
 778      * <th scope="row" style="text-align:left">{@code CL.in(D)} different module</th>
 779      * <td></td>
 780      * <td></td>
 781      * <td></td>
 782      * <td></td>
 783      * <td style="text-align:center">2R</td>
 784      * </tr>
 785      * <tr>
 786      * <td>{@code CL.in(D).in(C)} hop back to module</td>
 787      * <td></td>
 788      * <td></td>
 789      * <td></td>
 790      * <td></td>
 791      * <td style="text-align:center">2R</td>
 792      * </tr>
 793      * <tr>
 794      * <td>{@code PRI1 = privateLookupIn(C1,CL)}</td>
 795      * <td style="text-align:center">PRO</td>
 796      * <td style="text-align:center">PRI</td>
 797      * <td style="text-align:center">PAC</td>
 798      * <td style="text-align:center">MOD</td>
 799      * <td style="text-align:center">1R</td>
 800      * </tr>
 801      * <tr>
 802      * <td>{@code PRI1a = privateLookupIn(C,PRI1)}</td>
 803      * <td style="text-align:center">PRO</td>
 804      * <td style="text-align:center">PRI</td>
 805      * <td style="text-align:center">PAC</td>
 806      * <td style="text-align:center">MOD</td>
 807      * <td style="text-align:center">1R</td>
 808      * </tr>
 809      * <tr>
 810      * <td>{@code PRI1.in(C1)} same package</td>
 811      * <td></td>
 812      * <td></td>
 813      * <td style="text-align:center">PAC</td>
 814      * <td style="text-align:center">MOD</td>
 815      * <td style="text-align:center">1R</td>
 816      * </tr>
 817      * <tr>
 818      * <td>{@code PRI1.in(C1)} different package</td>
 819      * <td></td>
 820      * <td></td>
 821      * <td></td>
 822      * <td style="text-align:center">MOD</td>
 823      * <td style="text-align:center">1R</td>
 824      * </tr>
 825      * <tr>
 826      * <td>{@code PRI1.in(D)} different module</td>
 827      * <td></td>
 828      * <td></td>
 829      * <td></td>
 830      * <td></td>
 831      * <td style="text-align:center">2R</td>
 832      * </tr>
 833      * <tr>
 834      * <td>{@code PRI1.dropLookupMode(PROTECTED)}</td>
 835      * <td></td>
 836      * <td style="text-align:center">PRI</td>
 837      * <td style="text-align:center">PAC</td>
 838      * <td style="text-align:center">MOD</td>
 839      * <td style="text-align:center">1R</td>
 840      * </tr>
 841      * <tr>
 842      * <td>{@code PRI1.dropLookupMode(PRIVATE)}</td>
 843      * <td></td>
 844      * <td></td>
 845      * <td style="text-align:center">PAC</td>
 846      * <td style="text-align:center">MOD</td>
 847      * <td style="text-align:center">1R</td>
 848      * </tr>
 849      * <tr>
 850      * <td>{@code PRI1.dropLookupMode(PACKAGE)}</td>
 851      * <td></td>
 852      * <td></td>
 853      * <td></td>
 854      * <td style="text-align:center">MOD</td>
 855      * <td style="text-align:center">1R</td>
 856      * </tr>
 857      * <tr>
 858      * <td>{@code PRI1.dropLookupMode(MODULE)}</td>
 859      * <td></td>
 860      * <td></td>
 861      * <td></td>
 862      * <td></td>
 863      * <td style="text-align:center">1R</td>
 864      * </tr>
 865      * <tr>
 866      * <td>{@code PRI1.dropLookupMode(PUBLIC)}</td>
 867      * <td></td>
 868      * <td></td>
 869      * <td></td>
 870      * <td></td>
 871      * <td style="text-align:center">none</td>
 872      * <tr>
 873      * <td>{@code PRI2 = privateLookupIn(D,CL)}</td>
 874      * <td style="text-align:center">PRO</td>
 875      * <td style="text-align:center">PRI</td>
 876      * <td style="text-align:center">PAC</td>
 877      * <td></td>
 878      * <td style="text-align:center">2R</td>
 879      * </tr>
 880      * <tr>
 881      * <td>{@code privateLookupIn(D,PRI1)}</td>
 882      * <td style="text-align:center">PRO</td>
 883      * <td style="text-align:center">PRI</td>
 884      * <td style="text-align:center">PAC</td>
 885      * <td></td>
 886      * <td style="text-align:center">2R</td>
 887      * </tr>
 888      * <tr>
 889      * <td>{@code privateLookupIn(C,PRI2)} fails</td>
 890      * <td></td>
 891      * <td></td>
 892      * <td></td>
 893      * <td></td>
 894      * <td style="text-align:center">IAE</td>
 895      * </tr>
 896      * <tr>
 897      * <td>{@code PRI2.in(D2)} same package</td>
 898      * <td></td>
 899      * <td></td>
 900      * <td style="text-align:center">PAC</td>
 901      * <td></td>
 902      * <td style="text-align:center">2R</td>
 903      * </tr>
 904      * <tr>
 905      * <td>{@code PRI2.in(D2)} different package</td>
 906      * <td></td>
 907      * <td></td>
 908      * <td></td>
 909      * <td></td>
 910      * <td style="text-align:center">2R</td>
 911      * </tr>
 912      * <tr>
 913      * <td>{@code PRI2.in(C1)} hop back to module</td>
 914      * <td></td>
 915      * <td></td>
 916      * <td></td>
 917      * <td></td>
 918      * <td style="text-align:center">2R</td>
 919      * </tr>
 920      * <tr>
 921      * <td>{@code PRI2.in(E)} hop to third module</td>
 922      * <td></td>
 923      * <td></td>
 924      * <td></td>
 925      * <td></td>
 926      * <td style="text-align:center">none</td>
 927      * </tr>
 928      * <tr>
 929      * <td>{@code PRI2.dropLookupMode(PROTECTED)}</td>
 930      * <td></td>
 931      * <td style="text-align:center">PRI</td>
 932      * <td style="text-align:center">PAC</td>
 933      * <td></td>
 934      * <td style="text-align:center">2R</td>
 935      * </tr>
 936      * <tr>
 937      * <td>{@code PRI2.dropLookupMode(PRIVATE)}</td>
 938      * <td></td>
 939      * <td></td>
 940      * <td style="text-align:center">PAC</td>
 941      * <td></td>
 942      * <td style="text-align:center">2R</td>
 943      * </tr>
 944      * <tr>
 945      * <td>{@code PRI2.dropLookupMode(PACKAGE)}</td>
 946      * <td></td>
 947      * <td></td>
 948      * <td></td>
 949      * <td></td>
 950      * <td style="text-align:center">2R</td>
 951      * </tr>
 952      * <tr>
 953      * <td>{@code PRI2.dropLookupMode(MODULE)}</td>
 954      * <td></td>
 955      * <td></td>
 956      * <td></td>
 957      * <td></td>
 958      * <td style="text-align:center">2R</td>
 959      * </tr>
 960      * <tr>
 961      * <td>{@code PRI2.dropLookupMode(PUBLIC)}</td>
 962      * <td></td>
 963      * <td></td>
 964      * <td></td>
 965      * <td></td>
 966      * <td style="text-align:center">none</td>
 967      * </tr>
 968      * <tr>
 969      * <td>{@code CL.dropLookupMode(PROTECTED)}</td>
 970      * <td></td>
 971      * <td style="text-align:center">PRI</td>
 972      * <td style="text-align:center">PAC</td>
 973      * <td style="text-align:center">MOD</td>
 974      * <td style="text-align:center">1R</td>
 975      * </tr>
 976      * <tr>
 977      * <td>{@code CL.dropLookupMode(PRIVATE)}</td>
 978      * <td></td>
 979      * <td></td>
 980      * <td style="text-align:center">PAC</td>
 981      * <td style="text-align:center">MOD</td>
 982      * <td style="text-align:center">1R</td>
 983      * </tr>
 984      * <tr>
 985      * <td>{@code CL.dropLookupMode(PACKAGE)}</td>
 986      * <td></td>
 987      * <td></td>
 988      * <td></td>
 989      * <td style="text-align:center">MOD</td>
 990      * <td style="text-align:center">1R</td>
 991      * </tr>
 992      * <tr>
 993      * <td>{@code CL.dropLookupMode(MODULE)}</td>
 994      * <td></td>
 995      * <td></td>
 996      * <td></td>
 997      * <td></td>
 998      * <td style="text-align:center">1R</td>
 999      * </tr>
1000      * <tr>
1001      * <td>{@code CL.dropLookupMode(PUBLIC)}</td>
1002      * <td></td>
1003      * <td></td>
1004      * <td></td>
1005      * <td></td>
1006      * <td style="text-align:center">none</td>
1007      * </tr>
1008      * <tr>
1009      * <td>{@code PUB = publicLookup()}</td>
1010      * <td></td>
1011      * <td></td>
1012      * <td></td>
1013      * <td></td>
1014      * <td style="text-align:center">U</td>
1015      * </tr>
1016      * <tr>
1017      * <td>{@code PUB.in(D)} different module</td>
1018      * <td></td>
1019      * <td></td>
1020      * <td></td>
1021      * <td></td>
1022      * <td style="text-align:center">U</td>
1023      * </tr>
1024      * <tr>
1025      * <td>{@code PUB.in(D).in(E)} third module</td>
1026      * <td></td>
1027      * <td></td>
1028      * <td></td>
1029      * <td></td>
1030      * <td style="text-align:center">U</td>
1031      * </tr>
1032      * <tr>
1033      * <td>{@code PUB.dropLookupMode(UNCONDITIONAL)}</td>
1034      * <td></td>
1035      * <td></td>
1036      * <td></td>
1037      * <td></td>
1038      * <td style="text-align:center">none</td>
1039      * </tr>
1040      * <tr>
1041      * <td>{@code privateLookupIn(C1,PUB)} fails</td>
1042      * <td></td>
1043      * <td></td>
1044      * <td></td>
1045      * <td></td>
1046      * <td style="text-align:center">IAE</td>
1047      * </tr>
1048      * <tr>
1049      * <td>{@code ANY.in(X)}, for inaccessible <code>X</code></td>
1050      * <td></td>
1051      * <td></td>
1052      * <td></td>
1053      * <td></td>
1054      * <td style="text-align:center">none</td>
1055      * </tr>
1056      * </tbody>
1057      * </table>
1058      *
1059      * <p>
1060      * Notes:
1061      * <ul>
1062      * <li>Class {@code C} and class {@code C1} are in module {@code M1},
1063      *     but {@code D} and {@code D2} are in module {@code M2}, and {@code E}
1064      *     is in module {@code M3}. {@code X} stands for class which is inaccessible
1065      *     to the lookup. {@code ANY} stands for any of the example lookups.</li>
1066      * <li>{@code PRO} indicates {@link #PROTECTED} bit set,
1067      *     {@code PRI} indicates {@link #PRIVATE} bit set,
1068      *     {@code PAC} indicates {@link #PACKAGE} bit set,
1069      *     {@code MOD} indicates {@link #MODULE} bit set,
1070      *     {@code 1R} and {@code 2R} indicate {@link #PUBLIC} bit set,
1071      *     {@code U} indicates {@link #UNCONDITIONAL} bit set,
1072      *     {@code IAE} indicates {@code IllegalAccessException} thrown.</li>
1073      * <li>Public access comes in three kinds:
1074      * <ul>
1075      * <li>unconditional ({@code U}): the lookup assumes readability.
1076      *     The lookup has {@code null} previous lookup class.
1077      * <li>one-module-reads ({@code 1R}): the module access checking is
1078      *     performed with respect to the lookup class.  The lookup has {@code null}
1079      *     previous lookup class.
1080      * <li>two-module-reads ({@code 2R}): the module access checking is
1081      *     performed with respect to the lookup class and the previous lookup class.
1082      *     The lookup has a non-null previous lookup class which is in a
1083      *     different module from the current lookup class.
1084      * </ul>
1085      * <li>Any attempt to reach a third module loses all access.</li>
1086      * <li>If a target class {@code X} is not accessible to {@code Lookup::in}
1087      * all access modes are dropped.</li>
1088      * </ul>
1089      *
1090      * <h2><a id="secmgr"></a>Security manager interactions</h2>
1091      * Although bytecode instructions can only refer to classes in
1092      * a related class loader, this API can search for methods in any
1093      * class, as long as a reference to its {@code Class} object is
1094      * available.  Such cross-loader references are also possible with the
1095      * Core Reflection API, and are impossible to bytecode instructions
1096      * such as {@code invokestatic} or {@code getfield}.
1097      * There is a {@linkplain java.lang.SecurityManager security manager API}
1098      * to allow applications to check such cross-loader references.
1099      * These checks apply to both the {@code MethodHandles.Lookup} API
1100      * and the Core Reflection API
1101      * (as found on {@link java.lang.Class Class}).
1102      * <p>
1103      * If a security manager is present, member and class lookups are subject to
1104      * additional checks.
1105      * From one to three calls are made to the security manager.
1106      * Any of these calls can refuse access by throwing a
1107      * {@link java.lang.SecurityException SecurityException}.
1108      * Define {@code smgr} as the security manager,
1109      * {@code lookc} as the lookup class of the current lookup object,


1182      * If an application caches method handles for broad sharing,
1183      * it should use {@code publicLookup()} to create them.
1184      * If there is a lookup of {@code Class.forName}, it will fail,
1185      * and the application must take appropriate action in that case.
1186      * It may be that a later lookup, perhaps during the invocation of a
1187      * bootstrap method, can incorporate the specific identity
1188      * of the caller, making the method accessible.
1189      * <p style="font-size:smaller;">
1190      * The function {@code MethodHandles.lookup} is caller sensitive
1191      * so that there can be a secure foundation for lookups.
1192      * Nearly all other methods in the JSR 292 API rely on lookup
1193      * objects to check access requests.
1194      *
1195      * @revised 9
1196      */
1197     public static final
1198     class Lookup {
1199         /** The class on behalf of whom the lookup is being performed. */
1200         private final Class<?> lookupClass;
1201 
1202         /** previous lookup class */
1203         private final Class<?> prevLookupClass;
1204 
1205         /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */
1206         private final int allowedModes;
1207 
1208         static {
1209             Reflection.registerFieldsToFilter(Lookup.class, Set.of("lookupClass", "allowedModes"));
1210         }
1211 
1212         /** A single-bit mask representing {@code public} access,
1213          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1214          *  The value, {@code 0x01}, happens to be the same as the value of the
1215          *  {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}.
1216          *  <p>
1217          *  A {@code Lookup} with this lookup mode performs cross-module access check
1218          *  with respect to the {@linkplain #lookupClass() lookup class} and
1219          *  {@linkplain #previousLookupClass() previous lookup class} if present.
1220          */
1221         public static final int PUBLIC = Modifier.PUBLIC;
1222 
1223         /** A single-bit mask representing {@code private} access,
1224          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1225          *  The value, {@code 0x02}, happens to be the same as the value of the
1226          *  {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}.
1227          */
1228         public static final int PRIVATE = Modifier.PRIVATE;
1229 
1230         /** A single-bit mask representing {@code protected} access,
1231          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1232          *  The value, {@code 0x04}, happens to be the same as the value of the
1233          *  {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}.
1234          */
1235         public static final int PROTECTED = Modifier.PROTECTED;
1236 
1237         /** A single-bit mask representing {@code package} access (default access),
1238          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1239          *  The value is {@code 0x08}, which does not correspond meaningfully to
1240          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1241          */
1242         public static final int PACKAGE = Modifier.STATIC;
1243 
1244         /** A single-bit mask representing {@code module} access,
1245          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1246          *  The value is {@code 0x10}, which does not correspond meaningfully to
1247          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1248          *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
1249          *  with this lookup mode can access all public types in the module of the
1250          *  lookup class and public types in packages exported by other modules
1251          *  to the module of the lookup class.
1252          *  <p>
1253          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1254          *  previous lookup class} is always {@code null}.
1255          *
1256          *  @since 9
1257          *  @spec JPMS
1258          */
1259         public static final int MODULE = PACKAGE << 1;
1260 
1261         /** A single-bit mask representing {@code unconditional} access
1262          *  which may contribute to the result of {@link #lookupModes lookupModes}.
1263          *  The value is {@code 0x20}, which does not correspond meaningfully to
1264          *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
1265          *  A {@code Lookup} with this lookup mode assumes {@linkplain
1266          *  java.lang.Module#canRead(java.lang.Module) readability}.
1267          *  This lookup mode can access all public members of public types
1268          *  of all modules when the type is in a package that is {@link

1269          *  java.lang.Module#isExported(String) exported unconditionally}.
1270          *
1271          *  <p>
1272          *  If this lookup mode is set, the {@linkplain #previousLookupClass()
1273          *  previous lookup class} is always {@code null}.
1274          *
1275          *  @since 9
1276          *  @spec JPMS
1277          *  @see #publicLookup()
1278          */
1279         public static final int UNCONDITIONAL = PACKAGE << 2;
1280 
1281         private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL);
1282         private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);
1283         private static final int TRUSTED   = -1;
1284 
1285         /*
1286          * Adjust PUBLIC => PUBLIC|MODULE|UNCONDITIONAL
1287          * Adjust 0 => PACKAGE
1288          */
1289         private static int fixmods(int mods) {
1290             mods &= (ALL_MODES - PACKAGE - MODULE - UNCONDITIONAL);
1291             if (Modifier.isPublic(mods))
1292                 mods |= UNCONDITIONAL;
1293             return (mods != 0) ? mods : PACKAGE;
1294         }
1295 
1296         /** Tells which class is performing the lookup.  It is this class against
1297          *  which checks are performed for visibility and access permissions.
1298          *  <p>
1299          *  If this lookup object has a {@linkplain #previousLookupClass() previous lookup class},
1300          *  access checks are performed against both the lookup class and the previous lookup class.
1301          *  <p>
1302          *  The class implies a maximum level of access permission,
1303          *  but the permissions may be additionally limited by the bitmask
1304          *  {@link #lookupModes lookupModes}, which controls whether non-public members
1305          *  can be accessed.
1306          *  @return the lookup class, on behalf of which this lookup object finds members
1307          *  @see <a href="#cross-module-lookup">Cross-module lookups</a>
1308          */
1309         public Class<?> lookupClass() {
1310             return lookupClass;
1311         }
1312 
1313         /** Reports a lookup class in another module that this lookup object
1314          * was previously teleported from, or {@code null}.
1315          * <p>
1316          * A {@code Lookup} object produced by the factory methods, such as the
1317          * {@link #lookup() lookup()} and {@link #publicLookup() publicLookup()} method,
1318          * has {@code null} previous lookup class.
1319          * A {@code Lookup} object has a non-null previous lookup class
1320          * when this lookup was teleported from an old lookup class
1321          * in one module to a new lookup class in another module.
1322          *
1323          * @return the lookup class in another module that this lookup object was
1324          *         previously teleported from, or {@code null}
1325          * @since 14
1326          * @see #in(Class)
1327          * @see MethodHandles#privateLookupIn(Class, Lookup)
1328          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1329          */
1330         public Class<?> previousLookupClass() {
1331             return prevLookupClass;
1332         }
1333 
1334         // This is just for calling out to MethodHandleImpl.
1335         private Class<?> lookupClassOrNull() {
1336             return (allowedModes == TRUSTED) ? null : lookupClass;
1337         }
1338 
1339         /** Tells which access-protection classes of members this lookup object can produce.
1340          *  The result is a bit-mask of the bits
1341          *  {@linkplain #PUBLIC PUBLIC (0x01)},
1342          *  {@linkplain #PRIVATE PRIVATE (0x02)},
1343          *  {@linkplain #PROTECTED PROTECTED (0x04)},
1344          *  {@linkplain #PACKAGE PACKAGE (0x08)},
1345          *  {@linkplain #MODULE MODULE (0x10)},
1346          *  and {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}.
1347          *  <p>
1348          *  A freshly-created lookup object
1349          *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
1350          *  all possible bits set, except {@code UNCONDITIONAL}.
1351          *  A lookup object on a new lookup class
1352          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
1353          *  may have some mode bits set to zero.


1357          *  The purpose of this is to restrict access via the new lookup object,
1358          *  so that it can access only names which can be reached by the original
1359          *  lookup object, and also by the new lookup class.
1360          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
1361          *  @see #in
1362          *  @see #dropLookupMode
1363          *
1364          *  @revised 9
1365          *  @spec JPMS
1366          */
1367         public int lookupModes() {
1368             return allowedModes & ALL_MODES;
1369         }
1370 
1371         /** Embody the current class (the lookupClass) as a lookup class
1372          * for method handle creation.
1373          * Must be called by from a method in this package,
1374          * which in turn is called by a method not in this package.
1375          */
1376         Lookup(Class<?> lookupClass) {
1377             this(lookupClass, null, FULL_POWER_MODES);
1378             // make sure we haven't accidentally picked up a privileged class:
1379             checkUnprivilegedlookupClass(lookupClass);
1380         }
1381 
1382         private Lookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1383             assert prevLookupClass == null || ((allowedModes & MODULE) == 0
1384                     && prevLookupClass.getModule() != lookupClass.getModule());
1385 
1386             this.lookupClass = lookupClass;
1387             this.prevLookupClass = prevLookupClass;
1388             this.allowedModes = allowedModes;
1389         }
1390 
1391         private static Lookup newLookup(Class<?> lookupClass, Class<?> prevLookupClass, int allowedModes) {
1392             // make sure we haven't accidentally picked up a privileged class:
1393             checkUnprivilegedlookupClass(lookupClass);
1394             return new Lookup(lookupClass, prevLookupClass, allowedModes);
1395         }
1396 
1397         /**
1398          * Creates a lookup on the specified new lookup class.
1399          * The resulting object will report the specified
1400          * class as its own {@link #lookupClass() lookupClass}.
1401          *
1402          * <p>
1403          * However, the resulting {@code Lookup} object is guaranteed
1404          * to have no more access capabilities than the original.
1405          * In particular, access capabilities can be lost as follows:<ul>
1406          * <li>If the new lookup class is in a different module from the old one,
1407          * i.e. {@link #MODULE MODULE} access is lost.






1408          * <li>If the new lookup class is in a different package
1409          * than the old one, protected and default (package) members will not be accessible,
1410          * i.e. {@link #PROTECTED PROTECTED} and {@link #PACKAGE PACKAGE} access are lost.
1411          * <li>If the new lookup class is not within the same package member
1412          * as the old one, private members will not be accessible, and protected members
1413          * will not be accessible by virtue of inheritance,
1414          * i.e. {@link #PRIVATE PRIVATE} access is lost.
1415          * (Protected members may continue to be accessible because of package sharing.)
1416          * <li>If the new lookup class is not
1417          * {@linkplain #accessClass(Class) accessible} to this lookup,
1418          * then no members, not even public members, will be accessible
1419          * i.e. all access modes are lost.
1420          * <li>If the new lookup class, the old lookup class and the previous lookup class
1421          * are all in different modules i.e. teleporting to a third module,
1422          * all access modes are lost.
1423          * </ul>
1424          * <p>
1425          * The new previous lookup class is chosen as follows:
1426          * <ul>
1427          * <li>If the new lookup object has {@link #UNCONDITIONAL UNCONDITIONAL} bit,
1428          * the new previous lookup class is {@code null}.
1429          * <li>If the new lookup class is in the same module as the old lookup class,
1430          * the new previous lookup class is the old previous lookup class.
1431          * <li>If the new lookup class is in a different module from the old lookup class,
1432          * the new previous lookup class is the the old lookup class.
1433          *</ul>
1434          * <p>
1435          * The resulting lookup's capabilities for loading classes
1436          * (used during {@link #findClass} invocations)
1437          * are determined by the lookup class' loader,
1438          * which may change due to this operation.
1439          * <p>
1440          * @param requestedLookupClass the desired lookup class for the new lookup object
1441          * @return a lookup object which reports the desired lookup class, or the same object
1442          * if there is no change
1443          * @throws NullPointerException if the argument is null
1444          *
1445          * @revised 9
1446          * @spec JPMS
1447          * @see #accessClass(Class)
1448          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
1449          */
1450         public Lookup in(Class<?> requestedLookupClass) {
1451             Objects.requireNonNull(requestedLookupClass);
1452             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
1453                 return new Lookup(requestedLookupClass, null, FULL_POWER_MODES);
1454             if (requestedLookupClass == this.lookupClass)
1455                 return this;  // keep same capabilities
1456             int newModes = (allowedModes & FULL_POWER_MODES);
1457             Module fromModule = this.lookupClass.getModule();
1458             Module targetModule = requestedLookupClass.getModule();
1459             Class<?> plc = this.previousLookupClass();
1460             if ((this.allowedModes & UNCONDITIONAL) != 0) {
1461                 assert plc == null;
1462                 newModes = UNCONDITIONAL;
1463             } else if (fromModule != targetModule) {
1464                 if (plc != null && !VerifyAccess.isSameModule(plc, requestedLookupClass)) {
1465                     // allow hopping back and forth between fromModule and plc's module
1466                     // but not the third module
1467                     newModes = 0;
1468                 }
1469                 // drop MODULE access
1470                 newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
1471                 // teleport from this lookup class
1472                 plc = this.lookupClass;
1473             }
1474             if ((newModes & PACKAGE) != 0
1475                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
1476                 newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
1477             }
1478             // Allow nestmate lookups to be created without special privilege:
1479             if ((newModes & PRIVATE) != 0
1480                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
1481                 newModes &= ~(PRIVATE|PROTECTED);
1482             }
1483             if ((newModes & (PUBLIC|UNCONDITIONAL)) != 0
1484                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, this.prevLookupClass, allowedModes)) {
1485                 // The requested class it not accessible from the lookup class.
1486                 // No permissions.
1487                 newModes = 0;
1488             }
1489             return newLookup(requestedLookupClass, plc, newModes);


1490         }
1491 

1492         /**
1493          * Creates a lookup on the same lookup class which this lookup object
1494          * finds members, but with a lookup mode that has lost the given lookup mode.
1495          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
1496          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}.
1497          * {@link #PROTECTED PROTECTED} is always
1498          * dropped and so the resulting lookup mode will never have this access capability.
1499          * When dropping {@code PACKAGE} then the resulting lookup will not have {@code PACKAGE}
1500          * or {@code PRIVATE} access. When dropping {@code MODULE} then the resulting lookup will
1501          * not have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code PUBLIC}
1502          * is dropped then the resulting lookup has no access. If {@code UNCONDITIONAL}
1503          * is dropped then the resulting lookup has no access.
1504          *
1505          * @apiNote
1506          * A lookup with {@code PACKAGE} but not {@code PRIVATE} mode can safely
1507          * delegate non-public access within the package of the lookup class without
1508          * conferring private access.  A lookup with {@code MODULE} but not
1509          * {@code PACKAGE} mode can safely delegate {@code PUBLIC} access within
1510          * the module of the lookup class without conferring package access.
1511          * A lookup with a {@linkplain #previousLookupClass() previous lookup class}
1512          * (and {@code PUBLIC} but not {@code MODULE} mode) can safely delegate access
1513          * to public classes accessible to both the module of the lookup class
1514          * and the module of the previous lookup class.
1515          *
1516          * @param modeToDrop the lookup mode to drop
1517          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
1518          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
1519          * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE} or {@code UNCONDITIONAL}
1520          * @see MethodHandles#privateLookupIn
1521          * @since 9
1522          */
1523         public Lookup dropLookupMode(int modeToDrop) {
1524             int oldModes = lookupModes();
1525             int newModes = oldModes & ~(modeToDrop | PROTECTED);
1526             switch (modeToDrop) {
1527                 case PUBLIC: newModes &= ~(FULL_POWER_MODES); break;
1528                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
1529                 case PACKAGE: newModes &= ~(PRIVATE); break;
1530                 case PROTECTED:
1531                 case PRIVATE:
1532                 case UNCONDITIONAL: break;
1533                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
1534             }
1535             if (newModes == oldModes) return this;  // return self if no change
1536             return newLookup(lookupClass(), previousLookupClass(), newModes);
1537         }
1538 
1539         /**
1540          * Defines a class to the same class loader and in the same runtime package and
1541          * {@linkplain java.security.ProtectionDomain protection domain} as this lookup's
1542          * {@linkplain #lookupClass() lookup class}.
1543          *
1544          * <p> The {@linkplain #lookupModes() lookup modes} for this lookup must include
1545          * {@link #PACKAGE PACKAGE} access as default (package) members will be
1546          * accessible to the class. The {@code PACKAGE} lookup mode serves to authenticate
1547          * that the lookup object was created by a caller in the runtime package (or derived
1548          * from a lookup originally created by suitably privileged code to a target class in
1549          * the runtime package). </p>
1550          *
1551          * <p> The {@code bytes} parameter is the class bytes of a valid class file (as defined
1552          * by the <em>The Java Virtual Machine Specification</em>) with a class name in the
1553          * same package as the lookup class. </p>
1554          *
1555          * <p> This method does not run the class initializer. The class initializer may
1556          * run at a later time, as detailed in section 12.4 of the <em>The Java Language


1621             ProtectionDomain pd = cachedProtectionDomain;
1622             if (pd == null) {
1623                 cachedProtectionDomain = pd = protectionDomain(lookupClass);
1624             }
1625             return pd;
1626         }
1627 
1628         private ProtectionDomain protectionDomain(Class<?> clazz) {
1629             PrivilegedAction<ProtectionDomain> pa = clazz::getProtectionDomain;
1630             return AccessController.doPrivileged(pa);
1631         }
1632 
1633         // cached protection domain
1634         private volatile ProtectionDomain cachedProtectionDomain;
1635 
1636 
1637         // Make sure outer class is initialized first.
1638         static { IMPL_NAMES.getClass(); }
1639 
1640         /** Package-private version of lookup which is trusted. */
1641         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, null, TRUSTED);
1642 
1643         /** Version of lookup which is trusted minimally.
1644          *  It can only be used to create method handles to publicly accessible
1645          *  members in packages that are exported unconditionally.
1646          */
1647         static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, null, UNCONDITIONAL);
1648 
1649         private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
1650             String name = lookupClass.getName();
1651             if (name.startsWith("java.lang.invoke."))
1652                 throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
1653         }
1654 
1655         /**
1656          * Displays the name of the class from which lookups are to be made.
1657          * followed with "/" and the name of the {@linkplain #previousLookupClass()
1658          * previous lookup class} if present.
1659          * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.)
1660          * If there are restrictions on the access permitted to this lookup,
1661          * this is indicated by adding a suffix to the class name, consisting
1662          * of a slash and a keyword.  The keyword represents the strongest
1663          * allowed access, and is chosen as follows:
1664          * <ul>
1665          * <li>If no access is allowed, the suffix is "/noaccess".
1666          * <li>If only unconditional access is allowed, the suffix is "/publicLookup".
1667          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".

1668          * <li>If only public and module access are allowed, the suffix is "/module".
1669          * <li>If public and package access are allowed, the suffix is "/package".
1670          * <li>If public, package, and private access are allowed, the suffix is "/private".
1671          * </ul>
1672          * If none of the above cases apply, it is the case that full access
1673          * (public, module, package, private, and protected) is allowed.
1674          * In this case, no suffix is added.
1675          * This is true only of an object obtained originally from
1676          * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}.
1677          * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in}
1678          * always have restricted access, and will display a suffix.
1679          * <p>
1680          * (It may seem strange that protected access should be
1681          * stronger than private access.  Viewed independently from
1682          * package access, protected access is the first to be lost,
1683          * because it requires a direct subclass relationship between
1684          * caller and callee.)
1685          * @see #in
1686          *
1687          * @revised 9
1688          * @spec JPMS
1689          */
1690         @Override
1691         public String toString() {
1692             String cname = lookupClass.getName();
1693             if (prevLookupClass != null)
1694                 cname += "/" + prevLookupClass.getName();
1695             switch (allowedModes) {
1696             case 0:  // no privileges
1697                 return cname + "/noaccess";
1698             case UNCONDITIONAL:
1699                 return cname + "/publicLookup";
1700             case PUBLIC:
1701                 return cname + "/public";


1702             case PUBLIC|MODULE:
1703                 return cname + "/module";
1704             case PUBLIC|PACKAGE:
1705             case PUBLIC|MODULE|PACKAGE:
1706                 return cname + "/package";
1707             case FULL_POWER_MODES & (~PROTECTED):
1708             case FULL_POWER_MODES & ~(PROTECTED|MODULE):
1709                     return cname + "/private";
1710             case FULL_POWER_MODES:
1711             case FULL_POWER_MODES & (~MODULE):
1712                 return cname;
1713             case TRUSTED:
1714                 return "/trusted";  // internal only; not exported
1715             default:  // Should not happen, but it's a bitfield...
1716                 cname = cname + "/" + Integer.toHexString(allowedModes);
1717                 assert(false) : cname;
1718                 return cname;
1719             }
1720         }
1721 
1722         /**
1723          * Produces a method handle for a static method.
1724          * The type of the method handle will be that of the method.
1725          * (Since static methods do not take receivers, there is no
1726          * additional receiver argument inserted into the method handle type,
1727          * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.)
1728          * The method and all its argument types must be accessible to the lookup object.
1729          * <p>
1730          * The returned method handle will have
1731          * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if


1932          * load the requested class, and then determines whether the class is accessible to this lookup object.
1933          *
1934          * @param targetName the fully qualified name of the class to be looked up.
1935          * @return the requested class.
1936          * @exception SecurityException if a security manager is present and it
1937          *            <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1938          * @throws LinkageError if the linkage fails
1939          * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader.
1940          * @throws IllegalAccessException if the class is not accessible, using the allowed access
1941          * modes.
1942          * @exception SecurityException if a security manager is present and it
1943          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1944          * @since 9
1945          */
1946         public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException {
1947             Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader());
1948             return accessClass(targetClass);
1949         }
1950 
1951         /**
1952          * Determines if a class can be accessed from the lookup context defined by
1953          * this {@code Lookup} object. The static initializer of the class is not run.
1954          * <p>
1955          * If the {@code targetClass} is in the same module as the lookup class,
1956          * the lookup class is {@code LC} in module {@code M1} and
1957          * the previous lookup class is in module {@code M0} or
1958          * {@code null} if not present,
1959          * {@code targetClass} is accessible if and only if one of the following is true:
1960          * <ul>
1961          * <li>If this lookup has {@link #PRIVATE} access, {@code targetClass} is
1962          *     {@code LC} or other class in the same nest of {@code LC}.</li>
1963          * <li>If this lookup has {@link #PACKAGE} access, {@code targetClass} is
1964          *     in the same runtime package of {@code LC}.</li>
1965          * <li>If this lookup has {@link #MODULE} access, {@code targetClass} is
1966          *     a public type in {@code M1}.</li>
1967          * <li>If this lookup has {@link #PUBLIC} access, {@code targetClass} is
1968          *     a public type in a package exported by {@code M1} to at least  {@code M0}
1969          *     if the previous lookup class is present; otherwise, {@code targetClass}
1970          *     is a public type in a package exported by {@code M1} unconditionally.</li>
1971          * </ul>
1972          *
1973          * <p>
1974          * Otherwise, if this lookup has {@link #UNCONDITIONAL} access, this lookup
1975          * can access public types in all modules when the type is in a package
1976          * that is exported unconditionally.
1977          * <p>
1978          * Otherwise, the target class is in a different module from {@code lookupClass},
1979          * and if this lookup does not have {@code PUBLIC} access, {@code lookupClass}
1980          * is inaccessible.
1981          * <p>
1982          * Otherwise, if this lookup has no {@linkplain #previousLookupClass() previous lookup class},
1983          * {@code M1} is the module containing {@code lookupClass} and
1984          * {@code M2} is the module containing {@code targetClass},
1985          * then {@code targetClass} is accessible if and only if
1986          * <ul>
1987          * <li>{@code M1} reads {@code M2}, and
1988          * <li>{@code targetClass} is public and in a package exported by
1989          *     {@code M2} at least to {@code M1}.
1990          * </ul>
1991          * <p>
1992          * Otherwise, if this lookup has a {@linkplain #previousLookupClass() previous lookup class},
1993          * {@code M1} and {@code M2} are as before, and {@code M0} is the module
1994          * containing the previous lookup class, then {@code targetClass} is accessible
1995          * if and only if one of the following is true:
1996          * <ul>
1997          * <li>{@code targetClass} is in {@code M0} and {@code M1}
1998          *     {@linkplain Module#reads reads} {@code M0} and the type is
1999          *     in a package that is exported to at least {@code M1}.
2000          * <li>{@code targetClass} is in {@code M1} and {@code M0}
2001          *     {@linkplain Module#reads reads} {@code M1} and the type is
2002          *     in a package that is exported to at least {@code M0}.
2003          * <li>{@code targetClass} is in a third module {@code M2} and both {@code M0}
2004          *     and {@code M1} reads {@code M2} and the type is in a package
2005          *     that is exported to at least both {@code M0} and {@code M2}.
2006          * </ul>
2007          * <p>
2008          * Otherwise, {@code targetClass} is not accessible.
2009          *
2010          * @param targetClass the class to be access-checked
2011          * @return the class that has been access-checked

2012          * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access
2013          * modes.
2014          * @exception SecurityException if a security manager is present and it
2015          *                              <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
2016          * @since 9
2017          * @see <a href="#cross-module-lookup">Cross-module lookups</a>
2018          */
2019         public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException {
2020             if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, prevLookupClass, allowedModes)) {
2021                 throw new MemberName(targetClass).makeAccessException("access violation", this);
2022             }
2023             checkSecurityManager(targetClass, null);
2024             return targetClass;
2025         }
2026 
2027         /**
2028          * Produces an early-bound method handle for a virtual method.
2029          * It will bypass checks for overriding methods on the receiver,
2030          * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial}
2031          * instruction from within the explicitly specified {@code specialCaller}.
2032          * The type of the method handle will be that of the method,
2033          * with a suitably restricted receiver type prepended.
2034          * (The receiver type will be {@code specialCaller} or a subtype.)
2035          * The method and all its argument types must be accessible
2036          * to the lookup object.
2037          * <p>
2038          * Before method resolution,
2039          * if the explicitly specified caller class is not identical with the
2040          * lookup class, or if this lookup object does not have


2765 
2766         MemberName resolveOrNull(byte refKind, MemberName member) {
2767             // do this before attempting to resolve
2768             if (!isClassAccessible(member.getDeclaringClass())) {
2769                 return null;
2770             }
2771             Objects.requireNonNull(member.getName());
2772             Objects.requireNonNull(member.getType());
2773             return IMPL_NAMES.resolveOrNull(refKind, member, lookupClassOrNull());
2774         }
2775 
2776         void checkSymbolicClass(Class<?> refc) throws IllegalAccessException {
2777             if (!isClassAccessible(refc)) {
2778                 throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this);
2779             }
2780         }
2781 
2782         boolean isClassAccessible(Class<?> refc) {
2783             Objects.requireNonNull(refc);
2784             Class<?> caller = lookupClassOrNull();
2785             return caller == null || VerifyAccess.isClassAccessible(refc, caller, prevLookupClass, allowedModes);
2786         }
2787 
2788         /** Check name for an illegal leading "&lt;" character. */
2789         void checkMethodName(byte refKind, String name) throws NoSuchMethodException {
2790             if (name.startsWith("<") && refKind != REF_newInvokeSpecial)
2791                 throw new NoSuchMethodException("illegal method name: "+name);
2792         }
2793 
2794 
2795         /**
2796          * Find my trustable caller class if m is a caller sensitive method.
2797          * If this lookup object has private access, then the caller class is the lookupClass.
2798          * Otherwise, if m is caller-sensitive, throw IllegalAccessException.
2799          */
2800         Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException {
2801             Class<?> callerClass = null;
2802             if (MethodHandleNatives.isCallerSensitive(m)) {
2803                 // Only lookups with private access are allowed to resolve caller-sensitive methods
2804                 if (hasPrivateAccess()) {
2805                     callerClass = lookupClass;


2902                 // All arrays simply inherit Object.clone.
2903                 // But for access checking logic, we make Object.clone
2904                 // (normally protected) appear to be public.
2905                 // Later on, when the DirectMethodHandle is created,
2906                 // its leading argument will be restricted to the
2907                 // requested array type.
2908                 // N.B. The return type is not adjusted, because
2909                 // that is *not* the bytecode behavior.
2910                 mods ^= Modifier.PROTECTED | Modifier.PUBLIC;
2911             }
2912             if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) {
2913                 // cannot "new" a protected ctor in a different package
2914                 mods ^= Modifier.PROTECTED;
2915             }
2916             if (Modifier.isFinal(mods) &&
2917                     MethodHandleNatives.refKindIsSetter(refKind))
2918                 throw m.makeAccessException("unexpected set of a final field", this);
2919             int requestedModes = fixmods(mods);  // adjust 0 => PACKAGE
2920             if ((requestedModes & allowedModes) != 0) {
2921                 if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(),
2922                                                     mods, lookupClass(), previousLookupClass(), allowedModes))
2923                     return;
2924             } else {
2925                 // Protected members can also be checked as if they were package-private.
2926                 if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0
2927                         && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass()))
2928                     return;
2929             }
2930             throw m.makeAccessException(accessFailedMessage(refc, m), this);
2931         }
2932 
2933         String accessFailedMessage(Class<?> refc, MemberName m) {
2934             Class<?> defc = m.getDeclaringClass();
2935             int mods = m.getModifiers();
2936             // check the class first:
2937             boolean classOK = (Modifier.isPublic(defc.getModifiers()) &&
2938                                (defc == refc ||
2939                                 Modifier.isPublic(refc.getModifiers())));
2940             if (!classOK && (allowedModes & PACKAGE) != 0) {
2941                 // ignore previous lookup class to check if default package access
2942                 classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), null, FULL_POWER_MODES) &&
2943                            (defc == refc ||
2944                             VerifyAccess.isClassAccessible(refc, lookupClass(), null, FULL_POWER_MODES)));
2945             }
2946             if (!classOK)
2947                 return "class is not public";
2948             if (Modifier.isPublic(mods))
2949                 return "access to public member failed";  // (how?, module not readable?)
2950             if (Modifier.isPrivate(mods))
2951                 return "member is private";
2952             if (Modifier.isProtected(mods))
2953                 return "member is protected";
2954             return "member is private to package";
2955         }
2956 
2957         private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException {
2958             int allowedModes = this.allowedModes;
2959             if (allowedModes == TRUSTED)  return;
2960             if (!hasPrivateAccess()
2961                 || (specialCaller != lookupClass()
2962                        // ensure non-abstract methods in superinterfaces can be special-invoked
2963                     && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller))))
2964                 throw new MemberName(specialCaller).


< prev index next >