1 /*
  2  * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /* @test
 25  * @modules java.base/java.lang:open
 26  * @run junit/othervm test.DefineClassTest
 27  * @summary Basic test for java.lang.invoke.MethodHandles.Lookup.defineClass
 28  */
 29 
 30 package test;
 31 
 32 import java.lang.classfile.ClassFile;
 33 import java.lang.constant.ClassDesc;
 34 import java.lang.invoke.MethodHandles.Lookup;
 35 import java.lang.reflect.AccessFlag;
 36 import java.net.URL;
 37 import java.net.URLClassLoader;
 38 import java.nio.file.Files;
 39 import java.nio.file.Path;
 40 import java.nio.file.Paths;
 41 
 42 import static java.lang.classfile.ClassFile.ACC_PUBLIC;
 43 import static java.lang.classfile.ClassFile.ACC_STATIC;
 44 import static java.lang.constant.ConstantDescs.CD_Object;
 45 import static java.lang.constant.ConstantDescs.CLASS_INIT_NAME;
 46 import static java.lang.constant.ConstantDescs.INIT_NAME;
 47 import static java.lang.constant.ConstantDescs.MTD_void;
 48 import static java.lang.invoke.MethodHandles.*;
 49 import static java.lang.invoke.MethodHandles.Lookup.*;
 50 import static org.junit.jupiter.api.Assertions.*;
 51 import org.junit.jupiter.api.Test;
 52 
 53 public class DefineClassTest {
 54     private static final String THIS_PACKAGE = DefineClassTest.class.getPackageName();
 55     private static final ClassDesc CD_Runnable = Runnable.class.describeConstable().orElseThrow();
 56     private static final ClassDesc CD_MissingSuperClass = ClassDesc.of("MissingSuperClass");
 57 
 58     /**
 59      * Test that a class has the same class loader, and is in the same package and
 60      * protection domain, as a lookup class.
 61      */
 62     void testSameAbode(Class<?> clazz, Class<?> lc) {
 63         assertSame(lc.getClassLoader(), clazz.getClassLoader());
 64         assertEquals(lc.getPackageName(), clazz.getPackageName());
 65         assertSame(lc.getProtectionDomain(), clazz.getProtectionDomain());
 66     }
 67 
 68     /**
 69      * Tests that a class is discoverable by name using Class.forName and
 70      * lookup.findClass
 71      */
 72     void testDiscoverable(Class<?> clazz, Lookup lookup) throws Exception {
 73         String cn = clazz.getName();
 74         ClassLoader loader = clazz.getClassLoader();
 75         assertSame(clazz, Class.forName(cn, false, loader));
 76         assertSame(clazz, lookup.findClass(cn));
 77     }
 78 
 79     /**
 80      * Basic test of defineClass to define a class in the same package as test.
 81      */
 82     @Test
 83     public void testDefineClass() throws Exception {
 84         final String CLASS_NAME = THIS_PACKAGE + ".Foo";
 85         Lookup lookup = lookup();
 86         Class<?> clazz = lookup.defineClass(generateClass(CLASS_NAME));
 87 
 88         // test name
 89         assertEquals(CLASS_NAME, clazz.getName());
 90 
 91         // test loader/package/protection-domain
 92         testSameAbode(clazz, lookup.lookupClass());
 93 
 94         // test discoverable
 95         testDiscoverable(clazz, lookup);
 96 
 97         // attempt defineClass again
 98         var bytes = generateClass(CLASS_NAME);
 99         assertThrows(LinkageError.class, () -> lookup.defineClass(bytes));
100     }
101 
102     /**
103      * Test public/package/protected/private access from class defined with defineClass.
104      */
105     @Test
106     public void testAccess() throws Exception {
107         final String THIS_CLASS = this.getClass().getName();
108         final String CLASS_NAME = THIS_PACKAGE + ".Runner";
109         Lookup lookup = lookup();
110 
111         // public
112         byte[] classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method1");
113         testInvoke(lookup.defineClass(classBytes));
114 
115         // package
116         classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method2");
117         testInvoke(lookup.defineClass(classBytes));
118 
119         // protected (same package)
120         classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method3");
121         testInvoke(lookup.defineClass(classBytes));
122 
123         // private
124         classBytes = generateRunner(CLASS_NAME + nextNumber(), THIS_CLASS, "method4");
125         Class<?> clazz = lookup.defineClass(classBytes);
126         Runnable r = (Runnable) clazz.newInstance();
127         assertThrows(IllegalAccessError.class, r::run);
128     }
129 
130     public static void method1() { }
131     static void method2() { }
132     protected static void method3() { }
133     private static void method4() { }
134 
135     void testInvoke(Class<?> clazz) throws Exception {
136         Object obj = clazz.newInstance();
137         ((Runnable) obj).run();
138     }
139 
140     /**
141      * Test that defineClass does not run the class initializer
142      */
143     @Test
144     public void testInitializerNotRun() throws Exception {
145         final String THIS_CLASS = this.getClass().getName();
146         final String CLASS_NAME = THIS_PACKAGE + ".ClassWithClinit";
147 
148         byte[] classBytes = generateClassWithInitializer(CLASS_NAME, THIS_CLASS, "fail");
149         Class<?> clazz = lookup().defineClass(classBytes);
150 
151         // trigger initializer to run
152         var e = assertThrows(ExceptionInInitializerError.class, clazz::newInstance);
153         assertInstanceOf(IllegalCallerException.class, e.getCause());
154     }
155 
156     static void fail() { throw new IllegalCallerException(); }
157 
158 
159     /**
160      * Test defineClass to define classes in a package containing classes with
161      * different protection domains.
162      */
163     @Test
164     public void testTwoProtectionDomains() throws Exception {
165         Path here = Paths.get("");
166 
167         // p.C1 in one exploded directory
168         Path dir1 = Files.createTempDirectory(here, "classes");
169         Path p = Files.createDirectory(dir1.resolve("p"));
170         Files.write(p.resolve("C1.class"), generateClass("p.C1"));
171         URL url1 = dir1.toUri().toURL();
172 
173         // p.C2 in another exploded directory
174         Path dir2 = Files.createTempDirectory(here, "classes");
175         p = Files.createDirectory(dir2.resolve("p"));
176         Files.write(p.resolve("C2.class"), generateClass("p.C2"));
177         URL url2 = dir2.toUri().toURL();
178 
179         // load p.C1 and p.C2
180         ClassLoader loader = new URLClassLoader(new URL[] { url1, url2 });
181         Class<?> target1 = Class.forName("p.C1", false, loader);
182         Class<?> target2 = Class.forName("p.C2", false, loader);
183         assertSame(loader, target1.getClassLoader());
184         assertSame(loader, target1.getClassLoader());
185         assertNotEquals(target2.getProtectionDomain(), target1.getProtectionDomain());
186 
187         // protection domain 1
188         Lookup lookup1 = privateLookupIn(target1, lookup());
189 
190         Class<?> clazz = lookup1.defineClass(generateClass("p.Foo"));
191         testSameAbode(clazz, lookup1.lookupClass());
192         testDiscoverable(clazz, lookup1);
193 
194         // protection domain 2
195         Lookup lookup2 = privateLookupIn(target2, lookup());
196 
197         clazz = lookup2.defineClass(generateClass("p.Bar"));
198         testSameAbode(clazz, lookup2.lookupClass());
199         testDiscoverable(clazz, lookup2);
200     }
201 
202     /**
203      * Test defineClass defining a class to the boot loader
204      */
205     @Test
206     public void testBootLoader() throws Exception {
207         Lookup lookup = privateLookupIn(Thread.class, lookup());
208         assertNull(lookup.getClass().getClassLoader());
209 
210         Class<?> clazz = lookup.defineClass(generateClass("java.lang.Foo"));
211         assertEquals("java.lang.Foo", clazz.getName());
212         testSameAbode(clazz, Thread.class);
213         testDiscoverable(clazz, lookup);
214     }
215 
216     @Test
217     public void testWrongPackage() throws Exception {
218         assertThrows(IllegalArgumentException.class, () -> lookup().defineClass(generateClass("other.C")));
219     }
220 
221     @Test
222     public void testNoPackageAccess() throws Exception {
223         Lookup lookup = lookup().dropLookupMode(PACKAGE);
224         assertThrows(IllegalAccessException.class, () -> lookup.defineClass(generateClass(THIS_PACKAGE + ".C")));
225     }
226 
227     @Test
228     public void testTruncatedClassFile() throws Exception {
229         assertThrows(ClassFormatError.class, () -> lookup().defineClass(new byte[0]));
230     }
231 
232     @Test
233     public void testNull() throws Exception {
234         assertThrows(NullPointerException.class, () -> lookup().defineClass(null));
235     }
236 
237     @Test
238     public void testLinking() throws Exception {
239         assertThrows(NoClassDefFoundError.class, () -> lookup().defineClass(generateNonLinkableClass(THIS_PACKAGE + ".NonLinkableClass")));
240     }
241 
242     @Test
243     public void testModuleInfo() throws Exception {
244         assertThrows(IllegalArgumentException.class, () -> lookup().defineClass(generateModuleInfo()));
245     }
246 
247     /**
248      * Generates a class file with the given class name
249      */
250     byte[] generateClass(String className) {
251         return ClassFile.of().build(ClassDesc.of(className), clb -> {
252             clb.withFlags(AccessFlag.PUBLIC, AccessFlag.SUPER);
253             clb.withSuperclass(CD_Object);
254             clb.withMethodBody(INIT_NAME, MTD_void, PUBLIC, cob -> {
255                 cob.aload(0);
256                 cob.invokespecial(CD_Object, INIT_NAME, MTD_void);
257                 cob.return_();
258             });
259         });
260     }
261 
262     /**
263      * Generate a class file with the given class name. The class implements Runnable
264      * with a run method to invokestatic the given targetClass/targetMethod.
265      */
266     byte[] generateRunner(String className,
267                           String targetClass,
268                           String targetMethod) throws Exception {
269 
270         return ClassFile.of().build(ClassDesc.of(className), clb -> {
271             clb.withSuperclass(CD_Object);
272             clb.withInterfaceSymbols(CD_Runnable);
273             clb.withMethodBody(INIT_NAME, MTD_void, PUBLIC, cob -> {
274                 cob.aload(0);
275                 cob.invokespecial(CD_Object, INIT_NAME, MTD_void);
276                 cob.return_();
277             });
278             clb.withMethodBody("run", MTD_void, PUBLIC, cob -> {
279                 cob.invokestatic(ClassDesc.of(targetClass), targetMethod, MTD_void);
280                 cob.return_();
281             });
282         });
283     }
284 
285     /**
286      * Generate a class file with the given class name. The class will initializer
287      * to invokestatic the given targetClass/targetMethod.
288      */
289     byte[] generateClassWithInitializer(String className,
290                                         String targetClass,
291                                         String targetMethod) throws Exception {
292 
293         return ClassFile.of().build(ClassDesc.of(className), clb -> {
294             clb.withFlags(AccessFlag.PUBLIC, AccessFlag.SUPER);
295             clb.withSuperclass(CD_Object);
296             clb.withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, cob -> {
297                 cob.aload(0);
298                 cob.invokespecial(CD_Object, INIT_NAME, MTD_void);
299                 cob.return_();
300             });
301             clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, cob -> {
302                 cob.invokestatic(ClassDesc.of(targetClass), targetMethod, MTD_void);
303                 cob.return_();
304             });
305         });
306     }
307 
308     /**
309      * Generates a non-linkable class file with the given class name
310      */
311     byte[] generateNonLinkableClass(String className) {
312         return ClassFile.of().build(ClassDesc.of(className), clb -> {
313             clb.withFlags(AccessFlag.PUBLIC, AccessFlag.SUPER);
314             clb.withSuperclass(CD_MissingSuperClass);
315             clb.withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, cob -> {
316                 cob.aload(0);
317                 cob.invokespecial(CD_MissingSuperClass, INIT_NAME, MTD_void);
318                 cob.return_();
319             });
320         });
321     }
322 
323     /**
324      * Generates a class file with the given class name
325      */
326     byte[] generateModuleInfo() {
327         return ClassFile.of().build(ClassDesc.of("module-info"), cb -> cb.withFlags(AccessFlag.MODULE));
328     }
329 
330     private int nextNumber() {
331         return ++nextNumber;
332     }
333 
334     private int nextNumber;
335 }