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