1 /*
2 * Copyright (c) 2019, 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 /*
25 * @test
26 * @bug 8330467
27 * @modules jdk.compiler
28 * @library /test/lib
29 * @compile BadClassFile.jcod
30 * BadClassFile2.jcod
31 * BadClassFileVersion.jcod
32 * @build jdk.test.lib.Utils
33 * jdk.test.lib.compiler.CompilerUtils
34 * @run junit/othervm BasicTest
35 */
36
37 import java.io.File;
38 import java.io.IOException;
39 import java.lang.classfile.ClassFile;
40 import java.lang.constant.ClassDesc;
41 import java.lang.invoke.MethodHandles.Lookup;
42 import java.lang.reflect.Array;
43 import java.lang.reflect.Method;
44 import java.nio.charset.StandardCharsets;
45 import java.nio.file.Files;
46 import java.nio.file.Path;
47 import java.nio.file.Paths;
48 import java.util.Arrays;
49 import java.util.List;
50 import java.util.stream.Stream;
51
52 import jdk.test.lib.compiler.CompilerUtils;
53 import jdk.test.lib.Utils;
54
55 import static java.lang.classfile.ClassFile.*;
56 import static java.lang.constant.ConstantDescs.CD_Enum;
57 import static java.lang.constant.ConstantDescs.CD_Object;
58 import static java.lang.invoke.MethodHandles.lookup;
59 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.*;
60 import static org.junit.jupiter.api.Assertions.*;
61 import org.junit.jupiter.api.BeforeAll;
62 import org.junit.jupiter.api.Test;
63 import org.junit.jupiter.params.ParameterizedTest;
64 import org.junit.jupiter.params.provider.MethodSource;
65
66 interface HiddenTest {
67 void test();
68 }
69
70 public class BasicTest {
71
72 private static final Path SRC_DIR = Paths.get(Utils.TEST_SRC, "src");
73 private static final Path CLASSES_DIR = Paths.get("classes");
74 private static final Path CLASSES_10_DIR = Paths.get("classes_10");
75
76 private static byte[] hiddenClassBytes;
77
78 @BeforeAll
79 static void setup() throws IOException {
80 compileSources(SRC_DIR, CLASSES_DIR);
81 hiddenClassBytes = Files.readAllBytes(CLASSES_DIR.resolve("HiddenClass.class"));
82
83 // compile with --release 10 with no NestHost and NestMembers attribute
84 compileSources(SRC_DIR.resolve("Outer.java"), CLASSES_10_DIR, "--release", "10");
85 compileSources(SRC_DIR.resolve("EnclosingClass.java"), CLASSES_10_DIR, "--release", "10");
86 }
87
88 static void compileSources(Path sourceFile, Path dest, String... options) throws IOException {
89 Stream<String> ops = Stream.of("-cp", Utils.TEST_CLASSES + File.pathSeparator + CLASSES_DIR);
90 if (options != null && options.length > 0) {
91 ops = Stream.concat(ops, Arrays.stream(options));
92 }
93 if (!CompilerUtils.compile(sourceFile, dest, ops.toArray(String[]::new))) {
94 throw new RuntimeException("Compilation of the test failed: " + sourceFile);
95 }
96 }
97
98 static Class<?> defineHiddenClass(String name) throws Exception {
99 byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve(name + ".class"));
100 Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
101 assertHiddenClass(hc);
102 singletonNest(hc);
103 return hc;
104 }
105
106 // basic test on a hidden class
107 @Test
108 public void hiddenClass() throws Throwable {
109 HiddenTest t = (HiddenTest)defineHiddenClass("HiddenClass").newInstance();
110 t.test();
111
112 // sanity check
113 Class<?> c = t.getClass();
114 Class<?>[] intfs = c.getInterfaces();
115 assertTrue(c.isHidden());
116 assertFalse(c.isPrimitive());
117 assertEquals(1, intfs.length);
118 assertSame(HiddenTest.class, intfs[0]);
119 assertNull(c.getCanonicalName());
120
121 String hcName = "HiddenClass";
122 String hcSuffix = "0x[0-9a-f]+";
123 assertTrue(c.getName().matches(hcName + "/" + hcSuffix));
124 assertTrue(c.descriptorString().matches("L" + hcName + "." + hcSuffix + ";"), c.descriptorString());
125
126 // test array of hidden class
127 testHiddenArray(c);
128
129 // test setAccessible
130 checkSetAccessible(c, "realTest");
131 checkSetAccessible(c, "test");
132 }
133
134 // primitive class is not a hidden class
135 @Test
136 public void primitiveClass() {
137 assertFalse(int.class.isHidden());
138 assertFalse(String.class.isHidden());
139 }
140
141 private void testHiddenArray(Class<?> type) throws Exception {
142 // array of hidden class
143 Object array = Array.newInstance(type, 2);
144 Class<?> arrayType = array.getClass();
145 assertTrue(arrayType.isArray());
146 assertEquals(2, Array.getLength(array));
147 assertFalse(arrayType.isHidden());
148
149 String hcName = "HiddenClass";
150 String hcSuffix = "0x[0-9a-f]+";
151 assertTrue(arrayType.getName().matches("\\[" + "L" + hcName + "/" + hcSuffix + ";"));
152 assertTrue(arrayType.descriptorString().matches("\\[" + "L" + hcName + "." + hcSuffix + ";"));
153
154 assertTrue(arrayType.getComponentType().isHidden());
155 assertSame(type, arrayType.getComponentType());
156 Object t = type.newInstance();
157 Array.set(array, 0, t);
158 Object o = Array.get(array, 0);
159 assertSame(t, o);
160 }
161
162 private void checkSetAccessible(Class<?> c, String name, Class<?>... ptypes) throws Exception {
163 Method m = c.getDeclaredMethod(name, ptypes);
164 assertTrue(m.trySetAccessible());
165 m.setAccessible(true);
166 }
167
168 // Define a hidden class that uses lambda
169 // This verifies LambdaMetaFactory supports the caller which is a hidden class
170 @Test
171 public void testLambda() throws Throwable {
172 HiddenTest t = (HiddenTest)defineHiddenClass("Lambda").newInstance();
173 var e = assertThrows(Error.class, t::test);
174 assertEquals("thrown by " + t.getClass().getName(), e.getMessage());
175 }
176
177 // Define a hidden class that uses lambda and contains its implementation
178 // This verifies LambdaMetaFactory supports the caller which is a hidden class
179 @Test
180 public void testHiddenLambda() throws Throwable {
181 HiddenTest t = (HiddenTest)defineHiddenClass("HiddenLambda").newInstance();
182 var e = assertThrows(Error.class, t::test);
183 assertEquals("thrown by " + t.getClass().getName(), e.getMessage());
184 }
185
186 // Verify the nest host and nest members of a hidden class and hidden nestmate class
187 @Test
188 public void testHiddenNestHost() throws Throwable {
189 byte[] hc1 = hiddenClassBytes;
190 Lookup lookup1 = lookup().defineHiddenClass(hc1, false);
191 Class<?> host = lookup1.lookupClass();
192
193 byte[] hc2 = Files.readAllBytes(CLASSES_DIR.resolve("Lambda.class"));
194 Lookup lookup2 = lookup1.defineHiddenClass(hc2, false, NESTMATE);
195 Class<?> member = lookup2.lookupClass();
196
197 // test nest membership and reflection API
198 assertTrue(host.isNestmateOf(member));
199 assertSame(host, host.getNestHost());
200 // getNestHost and getNestMembers return the same value when calling
201 // on a nest member and the nest host
202 assertSame(host.getNestHost(), member.getNestHost());
203 assertArrayEquals(member.getNestMembers(), host.getNestMembers());
204 // getNestMembers includes the nest host that can be a hidden class but
205 // only includes static nest members
206 assertEquals(1, host.getNestMembers().length);
207 assertSame(host, host.getNestMembers()[0]);
208 }
209
210 private static Object[][] hiddenClasses() {
211 return new Object[][] {
212 new Object[] { "HiddenInterface", false },
213 new Object[] { "AbstractClass", false },
214 // a hidden annotation is useless because it cannot be referenced by any class
215 new Object[] { "HiddenAnnotation", false },
216 // class file with bad NestHost, NestMembers and InnerClasses or EnclosingMethod attribute
217 // define them as nestmate to verify Class::getNestHost and getNestMembers
218 new Object[] { "Outer", true },
219 new Object[] { "Outer$Inner", true },
220 new Object[] { "EnclosingClass", true },
221 new Object[] { "EnclosingClass$1", true },
222 };
223 }
224
225 /*
226 * Test that class file bytes that can be defined as a normal class
227 * can be successfully created as a hidden class even it might not
228 * make sense as a hidden class. For example, a hidden annotation
229 * is not useful as it cannot be referenced and an outer/inner class
230 * when defined as a hidden effectively becomes a final top-level class.
231 */
232 @ParameterizedTest
233 @MethodSource("hiddenClasses")
234 public void defineHiddenClass(String name, boolean nestmate) throws Exception {
235 byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve(name + ".class"));
236 Class<?> hc;
237 Class<?> host;
238 if (nestmate) {
239 hc = lookup().defineHiddenClass(bytes, false, NESTMATE).lookupClass();
240 host = lookup().lookupClass().getNestHost();
241 } else {
242 hc = lookup().defineHiddenClass(bytes, false).lookupClass();
243 host = hc;
244 }
245 assertSame(host, hc.getNestHost());
246 assertEquals(1, hc.getNestMembers().length);
247 assertSame(host, hc.getNestMembers()[0]);
248 }
249
250 private static Object[][] emptyClasses() {
251 return new Object[][] {
252 new Object[] { "EmptyHiddenSynthetic", ACC_SYNTHETIC },
253 new Object[] { "EmptyHiddenEnum", ACC_ENUM },
254 new Object[] { "EmptyHiddenAbstractClass", ACC_ABSTRACT },
255 new Object[] { "EmptyHiddenInterface", ACC_ABSTRACT|ACC_INTERFACE },
256 new Object[] { "EmptyHiddenAnnotation", ACC_ANNOTATION|ACC_ABSTRACT|ACC_INTERFACE },
257 };
258 }
259
260 /*
261 * Test if an empty class with valid access flags can be created as a hidden class
262 * as long as it does not violate the restriction of a hidden class.
263 *
264 * A meaningful enum type defines constants of that enum type. So
265 * enum class containing constants of its type should not be a hidden
266 * class.
267 */
268 @ParameterizedTest
269 @MethodSource("emptyClasses")
270 public void emptyHiddenClass(String name, int accessFlags) throws Exception {
271 byte[] bytes = (accessFlags == ACC_ENUM) ? classBytes(name, CD_Enum, accessFlags)
272 : classBytes(name, accessFlags);
273 Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
274 switch (accessFlags) {
275 case ACC_SYNTHETIC:
276 assertTrue(hc.isSynthetic());
277 assertFalse(hc.isEnum());
278 assertFalse(hc.isAnnotation());
279 assertFalse(hc.isInterface());
280 break;
281 case ACC_ENUM:
282 assertFalse(hc.isSynthetic());
283 assertTrue(hc.isEnum());
284 assertFalse(hc.isAnnotation());
285 assertFalse(hc.isInterface());
286 break;
287 case ACC_ABSTRACT:
288 assertFalse(hc.isSynthetic());
289 assertFalse(hc.isEnum());
290 assertFalse(hc.isAnnotation());
291 assertFalse(hc.isInterface());
292 break;
293 case ACC_ABSTRACT|ACC_INTERFACE:
294 assertFalse(hc.isSynthetic());
295 assertFalse(hc.isEnum());
296 assertFalse(hc.isAnnotation());
297 assertTrue(hc.isInterface());
298 break;
299 case ACC_ANNOTATION|ACC_ABSTRACT|ACC_INTERFACE:
300 assertFalse(hc.isSynthetic());
301 assertFalse(hc.isEnum());
302 assertTrue(hc.isAnnotation());
303 assertTrue(hc.isInterface());
304 break;
305 default:
306 throw new IllegalArgumentException("unexpected access flag: " + accessFlags);
307 }
308 assertTrue(hc.isHidden());
309 assertEquals(hc.getModifiers(), ACC_PUBLIC | accessFlags);
310 assertFalse(hc.isLocalClass());
311 assertFalse(hc.isMemberClass());
312 assertFalse(hc.isAnonymousClass());
313 assertFalse(hc.isArray());
314 }
315
316 // These class files can't be defined as hidden classes
317 private static Object[][] cantBeHiddenClasses() {
318 return new Object[][] {
319 // a hidden class can't be a field's declaring type
320 // enum class with static final HiddenEnum[] $VALUES:
321 new Object[] { "HiddenEnum" },
322 // supertype of this class is a hidden class
323 new Object[] { "HiddenSuper" },
324 // a record class whose equals(HiddenRecord, Object) method
325 // refers to a hidden class in the parameter type and fails
326 // verification. Perhaps this method signature should be reconsidered.
327 new Object[] { "HiddenRecord" },
328 };
329 }
330
331 /*
332 * These class files
333 */
334 @ParameterizedTest
335 @MethodSource("cantBeHiddenClasses")
336 public void failToDeriveAsHiddenClass(String name) throws Exception {
337 byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve(name + ".class"));
338 assertThrows(NoClassDefFoundError.class, () -> lookup().defineHiddenClass(bytes, false).lookupClass());
339 }
340
341 /*
342 * A hidden class can be successfully created but fails to be reflected
343 * if it refers to its own type in the descriptor.
344 * e.g. Class::getMethods resolves the declaring type of fields,
345 * parameter types and return type.
346 */
347 @Test
348 public void hiddenCantReflect() throws Throwable {
349 HiddenTest t = (HiddenTest)defineHiddenClass("HiddenCantReflect").newInstance();
350 t.test();
351
352 Class<?> c = t.getClass();
353 Class<?>[] intfs = c.getInterfaces();
354 assertEquals(1, intfs.length);
355 assertSame(HiddenTest.class, intfs[0]);
356
357 var e = assertThrows(NoClassDefFoundError.class, c::getDeclaredMethods);
358 Throwable x = e.getCause();
359 if (x == null || !(x instanceof ClassNotFoundException && x.getMessage().contains("HiddenCantReflect"))) {
360 throw e;
361 }
362 }
363
364 @Test
365 public void cantDefineModule() throws Throwable {
366 Path src = Paths.get("module-info.java");
367 Path dir = CLASSES_DIR.resolve("m");
368 Files.write(src, List.of("module m {}"), StandardCharsets.UTF_8);
369 compileSources(src, dir);
370
371 byte[] bytes = Files.readAllBytes(dir.resolve("module-info.class"));
372 assertThrows(IllegalArgumentException.class, () -> lookup().defineHiddenClass(bytes, false));
373 }
374
375 @Test
376 public void cantDefineClassInAnotherPackage() throws Throwable {
377 Path src = Paths.get("ClassInAnotherPackage.java");
378 Files.write(src, List.of("package p;", "public class ClassInAnotherPackage {}"), StandardCharsets.UTF_8);
379 compileSources(src, CLASSES_DIR);
380
381 byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve("p").resolve("ClassInAnotherPackage.class"));
382 assertThrows(IllegalArgumentException.class, () -> lookup().defineHiddenClass(bytes, false));
383 }
384
385 @Test
386 public void lessPrivilegedLookup() throws Throwable {
387 Lookup lookup = lookup().dropLookupMode(Lookup.PRIVATE);
388 assertThrows(IllegalAccessException.class, () -> lookup.defineHiddenClass(hiddenClassBytes, false));
389 }
390
391 @Test
392 public void badClassFileVersion() throws Throwable {
393 Path dir = Paths.get(System.getProperty("test.classes", "."));
394 byte[] bytes = Files.readAllBytes(dir.resolve("BadClassFileVersion.class"));
395 assertThrows(UnsupportedClassVersionError.class, () -> lookup().defineHiddenClass(bytes, false));
396 }
397
398 // malformed class files
399 private static Object[][] malformedClassFiles() throws IOException {
400 Path dir = Paths.get(System.getProperty("test.classes", "."));
401 return new Object[][] {
402 // `this_class` has invalid CP entry
403 new Object[] { Files.readAllBytes(dir.resolve("BadClassFile.class")) },
404 new Object[] { Files.readAllBytes(dir.resolve("BadClassFile2.class")) },
405 // truncated file
406 new Object[] { new byte[0] },
407 new Object[] { new byte[] {(byte) 0xCA, (byte) 0xBA, (byte) 0xBE, (byte) 0x00} },
408 };
409 }
410
411 @ParameterizedTest
412 @MethodSource("malformedClassFiles")
413 public void badClassFile(byte[] bytes) throws Throwable {
414 assertThrows(ClassFormatError.class, () -> lookup().defineHiddenClass(bytes, false));
415 }
416
417 private static Object[][] nestedTypesOrAnonymousClass() {
418 return new Object[][] {
419 // class file with bad InnerClasses or EnclosingMethod attribute
420 new Object[] { "Outer", null },
421 new Object[] { "Outer$Inner", "Outer" },
422 new Object[] { "EnclosingClass", null },
423 new Object[] { "EnclosingClass$1", "EnclosingClass" },
424 };
425 }
426
427 @ParameterizedTest
428 @MethodSource("nestedTypesOrAnonymousClass")
429 public void hasInnerClassesOrEnclosingMethodAttribute(String className, String badDeclaringClassName) throws Throwable {
430 byte[] bytes = Files.readAllBytes(CLASSES_10_DIR.resolve(className + ".class"));
431 Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
432 hiddenClassWithBadAttribute(hc, badDeclaringClassName);
433 }
434
435 // define a hidden class with static nest membership
436 @Test
437 public void hasStaticNestHost() throws Exception {
438 byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve("Outer$Inner.class"));
439 Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
440 hiddenClassWithBadAttribute(hc, "Outer");
441 }
442
443 @Test
444 public void hasStaticNestMembers() throws Throwable {
445 byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve("Outer.class"));
446 Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
447 assertHiddenClass(hc);
448 assertSame(hc, hc.getNestHost());
449 Class<?>[] members = hc.getNestMembers();
450 assertEquals(1, members.length);
451 assertSame(hc, members[0]);
452 }
453
454 // a hidden class with bad InnerClasses or EnclosingMethod attribute
455 private void hiddenClassWithBadAttribute(Class<?> hc, String badDeclaringClassName) {
456 assertTrue(hc.isHidden());
457 assertNull(hc.getCanonicalName());
458 assertTrue(hc.getName().contains("/"));
459
460 if (badDeclaringClassName == null) {
461 // the following reflection API assumes a good name in InnerClasses
462 // or EnclosingMethod attribute can successfully be resolved.
463 assertFalse(hc.getSimpleName().isEmpty());
464 assertFalse(hc.isAnonymousClass());
465 assertFalse(hc.isLocalClass());
466 assertFalse(hc.isMemberClass());
467 } else {
468 declaringClassNotFound(hc, badDeclaringClassName);
469 }
470
471 // validation of nest membership
472 assertSame(hc, hc.getNestHost());
473 // validate the static nest membership
474 Class<?>[] members = hc.getNestMembers();
475 assertEquals(1, members.length);
476 assertSame(hc, members[0]);
477 }
478
479 // Class::getSimpleName, Class::isMemberClass
480 private void declaringClassNotFound(Class<?> c, String cn) {
481 var e = assertThrows(NoClassDefFoundError.class, c::isMemberClass);
482 if (!e.getMessage().equals(cn)) {
483 throw e;
484 }
485 e = assertThrows(NoClassDefFoundError.class, c::getSimpleName);
486 if (!e.getMessage().equals(cn)) {
487 throw e;
488 }
489 }
490
491 private static void singletonNest(Class<?> hc) {
492 assertSame(hc, hc.getNestHost());
493 assertEquals(1, hc.getNestMembers().length);
494 assertSame(hc, hc.getNestMembers()[0]);
495 }
496
497 private static void assertHiddenClass(Class<?> hc) {
498 assertTrue(hc.isHidden());
499 assertNull(hc.getCanonicalName());
500 assertTrue(hc.getName().contains("/"));
501 assertFalse(hc.isAnonymousClass());
502 assertFalse(hc.isLocalClass());
503 assertFalse(hc.isMemberClass());
504 assertFalse(hc.getSimpleName().isEmpty()); // sanity check
505 }
506
507 private static byte[] classBytes(String classname, int accessFlags) {
508 return classBytes(classname, CD_Object, accessFlags);
509 }
510
511 private static byte[] classBytes(String classname, ClassDesc superType, int accessFlags) {
512 return ClassFile.of().build(ClassDesc.ofInternalName(classname), clb -> clb
513 .withVersion(JAVA_14_VERSION, 0)
514 .withFlags(accessFlags | ACC_PUBLIC)
515 .withSuperclass(superType));
516 }
517 }