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