< prev index next >

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

Print this page




  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.JavaLangAccess;
  29 import jdk.internal.access.SharedSecrets;

  30 import jdk.internal.module.IllegalAccessLogger;
  31 import jdk.internal.org.objectweb.asm.ClassReader;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.reflect.CallerSensitive;
  34 import jdk.internal.reflect.Reflection;
  35 import jdk.internal.vm.annotation.ForceInline;
  36 import sun.invoke.util.ValueConversions;
  37 import sun.invoke.util.VerifyAccess;
  38 import sun.invoke.util.Wrapper;
  39 import sun.reflect.misc.ReflectUtil;
  40 import sun.security.util.SecurityConstants;
  41 
  42 import java.lang.invoke.LambdaForm.BasicType;
  43 import java.lang.reflect.Constructor;
  44 import java.lang.reflect.Field;
  45 import java.lang.reflect.Member;
  46 import java.lang.reflect.Method;
  47 import java.lang.reflect.Modifier;
  48 import java.lang.reflect.ReflectPermission;
  49 import java.nio.ByteOrder;


1808          * this is not a valid binary class or interface name.</li>
1809          * </ul>
1810          * </li>
1811          * </ol>
1812          *
1813          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1814          * Linkage occurs as specified in JVMS 5.4.3, with the following adjustments:
1815          * <ul>
1816          * <li> During verification, whenever it is necessary to load the class named
1817          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1818          * made of any class loader.</li>
1819          *
1820          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1821          * by {@code this_class}, the symbolic reference is considered to be resolved to
1822          * {@code C} and resolution always succeeds immediately.</li>
1823          * </ul>
1824          *
1825          * <p> If the {@code initialize} parameter is {@code true},
1826          * then {@code C} is initialized by the Java Virtual Machine.
1827          *
1828          * <p>The newly created class or interface {@code C} is <em>hidden</em>, in the sense that
1829          * no other class or interface can refer to {@code C} via a constant pool entry.
1830          * That is, a hidden class or interface cannot be named as a supertype, a field type,
1831          * a method parameter type, or a method return type by any other class.
1832          * This is because a hidden class or interface does not have a binary name, so
1833          * there is no internal form available to record in any class's constant pool.
1834          * (Given the {@code Lookup} object returned this method, its lookup class
1835          * is a {@code Class} object for which {@link Class#getName()} returns a string
1836          * that is not a binary name.)
1837          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
1838          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
1839          * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
1840          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
1841          * JVM Tool Interface</a>.
1842          *
1843          * <p> If {@code options} has the {@link ClassOption#NESTMATE NESTMATE} option, then
1844          * the newly created class or interface {@code C} is a member of a nest. The nest
1845          * to which {@code C} belongs is not based on any {@code NestHost} attribute in
1846          * the {@code ClassFile} structure from which {@code C} was derived.








































1847          * Instead, the following rules determine the nest host of {@code C}:
1848          * <ul>
1849          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
1850          * been determined, then {@code H} be the nest host of the lookup class.</li>
1851          * <li>Otherwise, it is determined using the algorithm in JVMS 5.4.4, yielding {@code H}.</li>
1852          * <li>The nest host of {@code C} is determined to be {@code H}, the nest host of the lookup class.</li>


1853          * </ul>
1854          *
1855          * <p> If {@code options} has {@link ClassOption#WEAK WEAK} option, then
1856          * the newly created class or interface is <em>not strongly referenced</em> from
1857          * its defining class loader. Therefore, it may be unloaded while
1858          * its defining class loader is strongly reachable.
1859          *
1860          * <p> A hidden class or interface may be serializable, but this requires a custom
1861          * serialization mechanism in order to ensure that instances are properly serialized
1862          * and deserialized. The default serialization mechanism supports only classes and
1863          * interfaces that are discoverable by their class name.
1864          *
1865          * @param bytes the bytes that make up the class data,
1866          * in the format of a valid {@code class} file as defined by
1867          * <cite>The Java Virtual Machine Specification</cite>.
1868          * @param initialize if {@code true} the class will be initialized.
1869          * @param options {@linkplain ClassOption class options}
1870          * @return the {@code Lookup} object on the hidden class
1871          *
1872          * @throws IllegalAccessException if this {@code Lookup} does not have
1873          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1874          * @throws SecurityException if a security manager is present and it
1875          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1876          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1877          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1878          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1879          * {@bytes} denotes a class in a different package than the lookup class
1880          * @throws IncompatibleClassChangeError if the class or interface named as
1881          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1882          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1883          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1884          * {@code C} is {@code C} itself
1885          * @throws VerifyError if the newly created class cannot be verified
1886          * @throws LinkageError if the newly created class cannot be linked for any other reason
1887          * @throws NullPointerException if any parameter is {@code null}
1888          *
1889          * @since 15
1890          * @see Class#isHiddenClass()
1891          * @jvms 4.2.1 Binary Class and Interface Names
1892          * @jvms 4.2.2 Unqualified Names


1893          * @jvms 5.4.3.1 Class and Interface Resolution
1894          * @jvms 5.4.4 Access Control
1895          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
1896          * @jvms 5.4 Linking
1897          * @jvms 5.5 Initialization

1898          */
1899         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
1900                 throws IllegalAccessException
1901         {
1902             Objects.requireNonNull(bytes);
1903             Objects.requireNonNull(options);
1904 
1905             ensureDefineClassPermission();
1906             if (!hasFullPrivilegeAccess()) {
1907                 throw new IllegalAccessException(this + " does not have full privilege access");
1908             }
1909 
1910             Set<ClassOption> opts = options.length > 0 ? Set.of(options) : Set.of();
1911             return makeHiddenClassDefiner(bytes.clone(), opts).defineClassAsLookup(initialize);
1912         }
1913 
1914         /**
1915          * Creates a <em>hidden</em> class or interface from {@code bytes} with {@code classData},
1916          * returning a {@code Lookup} on the newly created class or interface.
1917          *
1918          * <p> This method is equivalent to calling
1919          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
1920          * as if the hidden class has a private static final unnamed field
1921          * pre-initialized with the given {@code classData}.
1922          * The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} method
1923          * can be used to retrieve the {@code classData}.
1924          *
1925          * @param bytes     the class bytes
1926          * @param classData pre-initialized class data
1927          * @param initialize if {@code true} the class will be initialized.
1928          * @param options   {@linkplain ClassOption class options}
1929          * @return the {@code Lookup} object on the hidden class
1930          *
1931          * @throws IllegalAccessException if this {@code Lookup} does not have


1944          * @throws LinkageError if the newly created class cannot be linked for any other reason
1945          * @throws NullPointerException if any parameter is {@code null}
1946          *
1947          * @since 15
1948          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1949          * @see Class#isHiddenClass()
1950          */
1951         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
1952                 throws IllegalAccessException
1953         {
1954             Objects.requireNonNull(bytes);
1955             Objects.requireNonNull(classData);
1956             Objects.requireNonNull(options);
1957 
1958             ensureDefineClassPermission();
1959             if (!hasFullPrivilegeAccess()) {
1960                 throw new IllegalAccessException(this + " does not have full privilege access");
1961             }
1962 
1963             Set<ClassOption> opts = options.length > 0 ? Set.of(options) : Set.of();
1964             return makeHiddenClassDefiner(bytes.clone(), opts).defineClassAsLookup(initialize, classData);

1965         }
1966 
1967         private ClassDefiner makeClassDefiner(byte[] bytes) {
1968             return new ClassDefiner(this, bytes, Set.of(), 0);
1969         }
1970 
1971         /**
1972          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
1973          * from the given bytes and options.
























1974          *
1975          * @param bytes class bytes
1976          * @param options class options

1977          * @return ClassDefiner that defines a hidden class of the given bytes and options
1978          */
1979         ClassDefiner makeHiddenClassDefiner(byte[] bytes, Set<ClassOption> options) {
1980             return new ClassDefiner(this, bytes, options, HIDDEN_CLASS);









1981         }
1982 
1983         /**
1984          * This method is only called by MethodHandleImpl.BindCaller.makeInjectedInvoker.

1985          *
1986          * @param name the name of the class and the name in the class bytes is ignored.
1987          * @param bytes class bytes
1988          * @return ClassDefiner that defines a hidden class of the given bytes

1989          */
1990         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes, int flags) {
1991             return new ClassDefiner(this, name, bytes, HIDDEN_CLASS|flags);










1992         }
1993 
1994         static class ClassDefiner {
1995             private final Lookup lookup;
1996             private final String name;
1997             private final byte[] bytes;
1998             private final int classFlags;
1999 
2000             // caller should make a defensive copy of the arguments if needed
2001             // before calling this constructor
2002             private ClassDefiner(Lookup lookup, byte[] bytes, Set<ClassOption> options, int flags) {


2003                 this.lookup = lookup;
2004                 this.bytes = bytes;
2005                 this.classFlags = flags | ClassOption.optionsToFlag(options);
2006                 this.name = className(bytes);
2007 
2008                 int index = name.lastIndexOf('.');
2009                 String pn = (index == -1) ? "" : name.substring(0, index);
2010                 if (!pn.equals(lookup.lookupClass().getPackageName())) {
2011                     throw newIllegalArgumentException(name + " not in same package as lookup class: " +
2012                             lookup.lookupClass().getName());
2013                 }
2014             }
2015 
2016             // skip package name check
2017             private ClassDefiner(Lookup lookup, String name, byte[] bytes, int flags) {

2018                 this.lookup = lookup;
2019                 this.bytes = bytes;
2020                 this.classFlags = flags;
2021                 this.name = name;
2022             }
2023 
2024             String className() {
2025                 return name;
2026             }
2027 
2028             Class<?> defineClass(boolean initialize) {
2029                 return defineClass(initialize, null);
2030             }
2031 
2032             Lookup defineClassAsLookup(boolean initialize) {
2033                 Class<?> c = defineClass(initialize, null);
2034                 return new Lookup(c, null, FULL_POWER_MODES);
2035             }
2036 
2037             /**


3724             return true;
3725         }
3726         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
3727                 throws ReflectiveOperationException {
3728             if (MethodHandleNatives.refKindIsField(refKind)) {
3729                 return getDirectFieldNoSecurityManager(refKind, defc, member);
3730             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
3731                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
3732             } else if (refKind == REF_newInvokeSpecial) {
3733                 return getDirectConstructorNoSecurityManager(defc, member);
3734             }
3735             // oops
3736             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
3737         }
3738 
3739         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
3740 
3741         /**
3742          * The set of class options that specify whether a hidden class created by
3743          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
3744          * Lookup::defineHiddenMethod} method is dynamically added as
3745          * a new member to the nest of a lookup class and whether a hidden class
3746          * is weak such that it may be unloaded while its defining class loader
3747          * is <a href="../ref/package.html#reachability">strongly reachable</a>.
3748          *
3749          * @since 15
3750          */
3751         public enum ClassOption {
3752             /**
3753              * This class option specifies the hidden class be added to
3754              * {@linkplain Class#getNestHost nest} of a lookup class as
3755              * a nestmate.
3756              *
3757              * <p> A hidden nestmate class has access to the private members of all
3758              * classes and interfaces in the same nest.
3759              *
3760              * @see Class#getNestHost()
3761              */
3762             NESTMATE(NESTMATE_CLASS),
3763 
3764             /**
3765              * This class option specifies the hidden class be weak so that
3766              * the class is not strongly referenced by its defining class loader.
3767              * A weak class may be unloaded while its defining class loader is
3768              * <a href="../ref/package.html#reachability">strongly reachable</a>.








3769              *
3770              * @jls 12.7 Unloading of Classes and Interfaces
3771              */
3772             WEAK(WEAK_CLASS);
3773 
3774             /* the flag value is used by VM at define class time */
3775             private final int flag;
3776             ClassOption(int flag) {
3777                 this.flag = flag;
3778             }
3779 
3780             static int optionsToFlag(Set<ClassOption> options) {
3781                 int flags = 0;
3782                 for (ClassOption cp : options) {
3783                     flags |= cp.flag;
3784                 }
3785                 return flags;
3786             }
3787         }
3788     }
3789 
3790     /**
3791      * Produces a method handle constructing arrays of a desired type,
3792      * as if by the {@code anewarray} bytecode.




  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.access.JavaLangAccess;
  29 import jdk.internal.access.SharedSecrets;
  30 import jdk.internal.misc.VM;
  31 import jdk.internal.module.IllegalAccessLogger;
  32 import jdk.internal.org.objectweb.asm.ClassReader;
  33 import jdk.internal.org.objectweb.asm.Opcodes;
  34 import jdk.internal.reflect.CallerSensitive;
  35 import jdk.internal.reflect.Reflection;
  36 import jdk.internal.vm.annotation.ForceInline;
  37 import sun.invoke.util.ValueConversions;
  38 import sun.invoke.util.VerifyAccess;
  39 import sun.invoke.util.Wrapper;
  40 import sun.reflect.misc.ReflectUtil;
  41 import sun.security.util.SecurityConstants;
  42 
  43 import java.lang.invoke.LambdaForm.BasicType;
  44 import java.lang.reflect.Constructor;
  45 import java.lang.reflect.Field;
  46 import java.lang.reflect.Member;
  47 import java.lang.reflect.Method;
  48 import java.lang.reflect.Modifier;
  49 import java.lang.reflect.ReflectPermission;
  50 import java.nio.ByteOrder;


1809          * this is not a valid binary class or interface name.</li>
1810          * </ul>
1811          * </li>
1812          * </ol>
1813          *
1814          * <p> After {@code C} is derived, it is linked by the Java Virtual Machine.
1815          * Linkage occurs as specified in JVMS 5.4.3, with the following adjustments:
1816          * <ul>
1817          * <li> During verification, whenever it is necessary to load the class named
1818          * {@code CN}, the attempt succeeds, producing class {@code C}. No request is
1819          * made of any class loader.</li>
1820          *
1821          * <li> On any attempt to resolve the entry in the run-time constant pool indicated
1822          * by {@code this_class}, the symbolic reference is considered to be resolved to
1823          * {@code C} and resolution always succeeds immediately.</li>
1824          * </ul>
1825          *
1826          * <p> If the {@code initialize} parameter is {@code true},
1827          * then {@code C} is initialized by the Java Virtual Machine.
1828          *
1829          * <p> The newly created class or interface {@code C} is <em>hidden</em>, in the sense that
1830          * no other class or interface can refer to {@code C} via a constant pool entry.
1831          * That is, a hidden class or interface cannot be named as a supertype, a field type,
1832          * a method parameter type, or a method return type by any other class.
1833          * This is because a hidden class or interface does not have a binary name, so
1834          * there is no internal form available to record in any class's constant pool.
1835          * (Given the {@code Lookup} object returned this method, its lookup class
1836          * is a {@code Class} object for which {@link Class#getName()} returns a string
1837          * that is not a binary name.)
1838          * A hidden class or interface is not discoverable by {@link Class#forName(String, boolean, ClassLoader)},
1839          * {@link ClassLoader#loadClass(String, boolean)}, or {@link #findClass(String)}, and
1840          * is not {@linkplain java.lang.instrument.Instrumentation#isModifiableClass(Class)
1841          * modifiable} by Java agents or tool agents using the <a href="{@docRoot}/../specs/jvmti.html">
1842          * JVM Tool Interface</a>.
1843          *
1844          * <p> A class or interface created by
1845          * {@linkplain ClassLoader#defineClass(String, byte[], int, int, ProtectionDomain)
1846          * a class loader} has a strong relationship with that class loader.
1847          * That is, every {@code Class} object contains a reference to the {@code ClassLoader}
1848          * that {@linkplain Class#getClassLoader() defined it}.
1849          * This means that a class created by a class loader may be unloaded if and
1850          * only if its defining loader is not reachable and thus may be reclaimed
1851          * by a garbage collector (JLS 12.7).
1852          *
1853          * By default, however, a hidden class or interface may be unloaded even if
1854          * the class loader that is marked as its defining loader is
1855          * <a href="../ref/package.html#reachability">reachable</a>.
1856          * This behavior is useful when a hidden class or interface serves multiple
1857          * classes defined by arbitrary class loaders.  In other cases, a hidden
1858          * class or interface may be linked to a single class (or a small number of classes)
1859          * with the same defining loader as the hidden class or interface.
1860          * In such cases, where the hidden class or interface must be coterminous
1861          * with a normal class or interface, the {@link ClassOption#STRONG STRONG}
1862          * option may be passed in {@code options}.
1863          * This arranges for a hidden class to have the same strong relationship
1864          * with the class loader marked as its defining loader,
1865          * as a normal class or interface has with its own defining loader.
1866          *
1867          * If {@code STRONG} is not used, then the invoker of {@code defineHiddenClass}
1868          * may still prevent a hidden class or interface from being
1869          * unloaded by ensuring that the {@code Class} object is reachable.
1870          *
1871          * <p> The unloading characteristics are set for each hidden class when it is
1872          * defined, and cannot be changed later.  An advantage of allowing hidden classes
1873          * to be unloaded independently of the loader deemed as their defining loader
1874          * is that a very large number of hidden classes may be created by an application.
1875          * In contrast, if {@code STRONG} is used, then the JVM may run out of memory,
1876          * just as if normal classes were created by class loaders.
1877          *
1878          * <p> Classes and interfaces in a nest are allowed to have mutual access to
1879          * their private members.  The nest relationship is determined by
1880          * the {@code NestHost} attribute (JVMS 4.7.28) and
1881          * the {@code NestMembers} attribute (JVMS 4.7.29) in a {@code class} file.
1882          * By default, a hidden class belongs to a nest consisting only of itself
1883          * because a hidden class has no binary name.
1884          * The {@link ClassOption#NESTMATE NESTMATE} option can be passed in {@code options}
1885          * to create a hidden class or interface {@code C} as a member of a nest.
1886          * The nest to which {@code C} belongs is not based on any {@code NestHost} attribute
1887          * in the {@code ClassFile} structure from which {@code C} was derived.
1888          * Instead, the following rules determine the nest host of {@code C}:
1889          * <ul>
1890          * <li>If the nest host of the lookup class of this {@code Lookup} has previously
1891          *     been determined, then let {@code H} be the nest host of the lookup class.
1892          *     Otherwise, the nest host of the lookup class is determined using the
1893          *     algorithm in JVMS 5.4.4, yielding {@code H}.</li>
1894          * <li>The nest host of {@code C} is determined to be {@code H},
1895          *     the nest host of the lookup class.</li>
1896          * </ul>
1897          *





1898          * <p> A hidden class or interface may be serializable, but this requires a custom
1899          * serialization mechanism in order to ensure that instances are properly serialized
1900          * and deserialized. The default serialization mechanism supports only classes and
1901          * interfaces that are discoverable by their class name.
1902          *
1903          * @param bytes the bytes that make up the class data,
1904          * in the format of a valid {@code class} file as defined by
1905          * <cite>The Java Virtual Machine Specification</cite>.
1906          * @param initialize if {@code true} the class will be initialized.
1907          * @param options {@linkplain ClassOption class options}
1908          * @return the {@code Lookup} object on the hidden class
1909          *
1910          * @throws IllegalAccessException if this {@code Lookup} does not have
1911          * {@linkplain #hasFullPrivilegeAccess() full privilege} access
1912          * @throws SecurityException if a security manager is present and it
1913          * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a>
1914          * @throws ClassFormatError if {@code bytes} is not a {@code ClassFile} structure
1915          * @throws UnsupportedClassVersionError if {@code bytes} is not of a supported major or minor version
1916          * @throws IllegalArgumentException if {@code bytes} is not a class or interface or
1917          * {@bytes} denotes a class in a different package than the lookup class
1918          * @throws IncompatibleClassChangeError if the class or interface named as
1919          * the direct superclass of {@code C} is in fact an interface, or if any of the classes
1920          * or interfaces named as direct superinterfaces of {@code C} are not in fact interfaces
1921          * @throws ClassCircularityError if any of the superclasses or superinterfaces of
1922          * {@code C} is {@code C} itself
1923          * @throws VerifyError if the newly created class cannot be verified
1924          * @throws LinkageError if the newly created class cannot be linked for any other reason
1925          * @throws NullPointerException if any parameter is {@code null}
1926          *
1927          * @since 15
1928          * @see Class#isHiddenClass()
1929          * @jvms 4.2.1 Binary Class and Interface Names
1930          * @jvms 4.2.2 Unqualified Names
1931          * @jvms 4.7.28 The {@code NestHost} Attribute
1932          * @jvms 4.7.29 The {@code NestMembers} Attribute
1933          * @jvms 5.4.3.1 Class and Interface Resolution
1934          * @jvms 5.4.4 Access Control
1935          * @jvms 5.3.5 Deriving a {@code Class} from a {@code class} File Representation
1936          * @jvms 5.4 Linking
1937          * @jvms 5.5 Initialization
1938          * @jls 12.7 Unloading of Classes and Interfaces
1939          */
1940         public Lookup defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
1941                 throws IllegalAccessException
1942         {
1943             Objects.requireNonNull(bytes);
1944             Objects.requireNonNull(options);
1945 
1946             ensureDefineClassPermission();
1947             if (!hasFullPrivilegeAccess()) {
1948                 throw new IllegalAccessException(this + " does not have full privilege access");
1949             }
1950 
1951             Set<ClassOption> opts = options.length > 0 ? Set.of(options) : Set.of();
1952             return makeHiddenClassDefiner(bytes.clone(), opts, false).defineClassAsLookup(initialize);
1953         }
1954 
1955         /**
1956          * Creates a <em>hidden</em> class or interface from {@code bytes} with {@code classData},
1957          * returning a {@code Lookup} on the newly created class or interface.
1958          *
1959          * <p> This method is equivalent to calling
1960          * {@link #defineHiddenClass(byte[], boolean, ClassOption...) defineHiddenClass(bytes, initialize, options)}
1961          * as if the hidden class has a private static final unnamed field
1962          * pre-initialized with the given {@code classData}.
1963          * The {@link MethodHandles#classData(Lookup, String, Class) MethodHandles::classData} method
1964          * can be used to retrieve the {@code classData}.
1965          *
1966          * @param bytes     the class bytes
1967          * @param classData pre-initialized class data
1968          * @param initialize if {@code true} the class will be initialized.
1969          * @param options   {@linkplain ClassOption class options}
1970          * @return the {@code Lookup} object on the hidden class
1971          *
1972          * @throws IllegalAccessException if this {@code Lookup} does not have


1985          * @throws LinkageError if the newly created class cannot be linked for any other reason
1986          * @throws NullPointerException if any parameter is {@code null}
1987          *
1988          * @since 15
1989          * @see Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
1990          * @see Class#isHiddenClass()
1991          */
1992         public Lookup defineHiddenClassWithClassData(byte[] bytes, Object classData, boolean initialize, ClassOption... options)
1993                 throws IllegalAccessException
1994         {
1995             Objects.requireNonNull(bytes);
1996             Objects.requireNonNull(classData);
1997             Objects.requireNonNull(options);
1998 
1999             ensureDefineClassPermission();
2000             if (!hasFullPrivilegeAccess()) {
2001                 throw new IllegalAccessException(this + " does not have full privilege access");
2002             }
2003 
2004             Set<ClassOption> opts = options.length > 0 ? Set.of(options) : Set.of();
2005             return makeHiddenClassDefiner(bytes.clone(), opts, false)
2006                        .defineClassAsLookup(initialize, classData);
2007         }
2008 
2009         private ClassDefiner makeClassDefiner(byte[] bytes) {
2010             return new ClassDefiner(this, bytes, STRONG_LOADER_LINK);
2011         }
2012 
2013         /**
2014          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2015          * from the given bytes.
2016          *
2017          * @param bytes   class bytes
2018          * @return ClassDefiner that defines a hidden class of the given bytes.
2019          */
2020         ClassDefiner makeHiddenClassDefiner(byte[] bytes) {
2021             return makeHiddenClassDefiner(bytes, Set.of(), false);
2022         }
2023 
2024         /**
2025          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2026          * from the given bytes.
2027          *
2028          * @param name    fully-qualified name that specifies the prefix of the hidden class
2029          * @param bytes   class bytes
2030          * @return ClassDefiner that defines a hidden class of the given bytes.
2031          */
2032         ClassDefiner makeHiddenClassDefiner(String name, byte[] bytes) {
2033             return makeHiddenClassDefiner(name, bytes, Set.of(), false);
2034         }
2035 
2036         /**
2037          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2038          * from the given bytes and options.  This method will read the class file
2039          * and obtain the class name.
2040          *
2041          * @param bytes   class bytes
2042          * @param options class options
2043          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2044          * @return ClassDefiner that defines a hidden class of the given bytes and options
2045          */
2046         ClassDefiner makeHiddenClassDefiner(byte[] bytes,
2047                                             Set<ClassOption> options,
2048                                             boolean accessVmAnnotations) {
2049             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2050             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2051                 // jdk.internal.vm.annotations are permitted for classes
2052                 // defined to boot loader and platform loader
2053                 flags |= ACCESS_VM_ANNOTATIONS;
2054             }
2055 
2056             return new ClassDefiner(this, bytes, flags);
2057         }
2058 
2059         /**
2060          * Returns a ClassDefiner that creates a {@code Class} object of a hidden class
2061          * from the given bytes and options.
2062          *
2063          * @param name the name of the class and the name in the class bytes is ignored.
2064          * @param bytes class bytes
2065          * @param options class options
2066          * @param accessVmAnnotations true to give the hidden class access to VM annotations
2067          */
2068         ClassDefiner makeHiddenClassDefiner(String name,
2069                                             byte[] bytes,
2070                                             Set<ClassOption> options,
2071                                             boolean accessVmAnnotations) {
2072             int flags = HIDDEN_CLASS | ClassOption.optionsToFlag(options);
2073             if (accessVmAnnotations | VM.isSystemDomainLoader(lookupClass.getClassLoader())) {
2074                 // jdk.internal.vm.annotations are permitted for classes
2075                 // defined to boot loader and platform loader
2076                 flags |= ACCESS_VM_ANNOTATIONS;
2077             }
2078 
2079             return new ClassDefiner(this, name, bytes, flags);
2080         }
2081 
2082         static class ClassDefiner {
2083             private final Lookup lookup;
2084             private final String name;
2085             private final byte[] bytes;
2086             private final int classFlags;
2087 
2088             // caller should make a defensive copy of the arguments if needed
2089             // before calling this constructor
2090             private ClassDefiner(Lookup lookup, byte[] bytes, int flags) {
2091                 // defining an ordinary class which must be a strongly referenced by its defining loader
2092                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2093                 this.lookup = lookup;
2094                 this.bytes = bytes;
2095                 this.classFlags = flags;
2096                 this.name = className(bytes);
2097 
2098                 int index = name.lastIndexOf('.');
2099                 String pn = (index == -1) ? "" : name.substring(0, index);
2100                 if (!pn.equals(lookup.lookupClass().getPackageName())) {
2101                     throw newIllegalArgumentException(name + " not in same package as lookup class: " +
2102                             lookup.lookupClass().getName());
2103                 }
2104             }
2105 
2106             // skip package name check
2107             private ClassDefiner(Lookup lookup, String name, byte[] bytes, int flags) {
2108                 assert ((flags & HIDDEN_CLASS) != 0 || (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK);
2109                 this.lookup = lookup;
2110                 this.bytes = bytes;
2111                 this.classFlags = flags;
2112                 this.name = name;
2113             }
2114 
2115             String className() {
2116                 return name;
2117             }
2118 
2119             Class<?> defineClass(boolean initialize) {
2120                 return defineClass(initialize, null);
2121             }
2122 
2123             Lookup defineClassAsLookup(boolean initialize) {
2124                 Class<?> c = defineClass(initialize, null);
2125                 return new Lookup(c, null, FULL_POWER_MODES);
2126             }
2127 
2128             /**


3815             return true;
3816         }
3817         private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member)
3818                 throws ReflectiveOperationException {
3819             if (MethodHandleNatives.refKindIsField(refKind)) {
3820                 return getDirectFieldNoSecurityManager(refKind, defc, member);
3821             } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
3822                 return getDirectMethodNoSecurityManager(refKind, defc, member, findBoundCallerLookup(member));
3823             } else if (refKind == REF_newInvokeSpecial) {
3824                 return getDirectConstructorNoSecurityManager(defc, member);
3825             }
3826             // oops
3827             throw newIllegalArgumentException("bad MethodHandle constant #"+member);
3828         }
3829 
3830         static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>();
3831 
3832         /**
3833          * The set of class options that specify whether a hidden class created by
3834          * {@link Lookup#defineHiddenClass(byte[], boolean, ClassOption...)
3835          * Lookup::defineHiddenClass} method is dynamically added as a new member
3836          * to the nest of a lookup class and/or whether a hidden class has
3837          * a strong relationship with the class loader marked as its defining loader.

3838          *
3839          * @since 15
3840          */
3841         public enum ClassOption {
3842             /**
3843              * This class option specifies the hidden class be added to
3844              * {@linkplain Class#getNestHost nest} of a lookup class as
3845              * a nestmate.
3846              *
3847              * <p> A hidden nestmate class has access to the private members of all
3848              * classes and interfaces in the same nest.
3849              *
3850              * @see Class#getNestHost()
3851              */
3852             NESTMATE(NESTMATE_CLASS),
3853 
3854             /**
3855              *
3856              * This class option specifies the hidden class to have a <em>strong</em>
3857              * relationship with the class loader marked as its defining loader,
3858              * as a normal class or interface has with its own defining loader.
3859              * This means that the hidden class may be unloaded if and only if
3860              * its defining loader is not reachable and thus may be reclaimed
3861              * by a garbage collector (JLS 12.7).
3862              *
3863              * <p> By default, a hidden class or interface may be unloaded
3864              * even if the class loader that is marked as its defining loader is
3865              * <a href="../ref/package.html#reachability">reachable</a>.
3866 
3867              *
3868              * @jls 12.7 Unloading of Classes and Interfaces
3869              */
3870             STRONG(STRONG_LOADER_LINK);
3871 
3872             /* the flag value is used by VM at define class time */
3873             private final int flag;
3874             ClassOption(int flag) {
3875                 this.flag = flag;
3876             }
3877 
3878             static int optionsToFlag(Set<ClassOption> options) {
3879                 int flags = 0;
3880                 for (ClassOption cp : options) {
3881                     flags |= cp.flag;
3882                 }
3883                 return flags;
3884             }
3885         }
3886     }
3887 
3888     /**
3889      * Produces a method handle constructing arrays of a desired type,
3890      * as if by the {@code anewarray} bytecode.


< prev index next >