1 /*
  2  * Copyright (c) 2019, 2020, 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  * @modules java.base/jdk.internal.org.objectweb.asm
 27  *          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 testng/othervm BasicTest
 35  */
 36 
 37 import java.io.File;
 38 import java.io.IOException;
 39 import java.lang.invoke.MethodHandles.Lookup;
 40 
 41 import static java.lang.invoke.MethodHandles.lookup;
 42 import static java.lang.invoke.MethodHandles.Lookup.ClassOption.*;
 43 
 44 import java.lang.reflect.AccessFlag;
 45 import java.lang.reflect.Array;
 46 import java.lang.reflect.Method;
 47 import java.nio.charset.StandardCharsets;
 48 import java.nio.file.Files;
 49 import java.nio.file.Path;
 50 import java.nio.file.Paths;
 51 import java.util.Arrays;
 52 import java.util.List;
 53 import java.util.stream.Stream;
 54 
 55 import jdk.internal.org.objectweb.asm.ClassWriter;
 56 import jdk.internal.org.objectweb.asm.Type;
 57 import jdk.test.lib.compiler.CompilerUtils;
 58 import jdk.test.lib.Utils;
 59 
 60 import org.testng.annotations.BeforeTest;
 61 import org.testng.annotations.DataProvider;
 62 import org.testng.annotations.Test;
 63 
 64 import static jdk.internal.org.objectweb.asm.Opcodes.*;
 65 import static org.testng.Assert.*;
 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     @BeforeTest
 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         assertTrue(c.getCanonicalName() == null);
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         assertTrue(Array.getLength(array) == 2);
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         assertTrue(arrayType.getComponentType() == type);
157         Object t = type.newInstance();
158         Array.set(array, 0, t);
159         Object o = Array.get(array, 0);
160         assertTrue(o == t);
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         try {
175             t.test();
176         } catch (Error e) {
177             if (!e.getMessage().equals("thrown by " + t.getClass().getName())) {
178                 throw e;
179             }
180         }
181     }
182 
183     // Verify the nest host and nest members of a hidden class and hidden nestmate class
184     @Test
185     public void testHiddenNestHost() throws Throwable {
186         byte[] hc1 = hiddenClassBytes;
187         Lookup lookup1 = lookup().defineHiddenClass(hc1, false);
188         Class<?> host = lookup1.lookupClass();
189 
190         byte[] hc2 = Files.readAllBytes(CLASSES_DIR.resolve("Lambda.class"));
191         Lookup lookup2 = lookup1.defineHiddenClass(hc2, false, NESTMATE);
192         Class<?> member = lookup2.lookupClass();
193 
194         // test nest membership and reflection API
195         assertTrue(host.isNestmateOf(member));
196         assertTrue(host.getNestHost() == host);
197         // getNestHost and getNestMembers return the same value when calling
198         // on a nest member and the nest host
199         assertTrue(member.getNestHost() == host.getNestHost());
200         assertTrue(Arrays.equals(member.getNestMembers(), host.getNestMembers()));
201         // getNestMembers includes the nest host that can be a hidden class but
202         // only includes static nest members
203         assertTrue(host.getNestMembers().length == 1);
204         assertTrue(host.getNestMembers()[0] == host);
205     }
206 
207     @DataProvider(name = "hiddenClasses")
208     private Object[][] hiddenClasses() {
209         return new Object[][] {
210                 new Object[] { "HiddenInterface", false },
211                 new Object[] { "AbstractClass", false },
212                 // a hidden annotation is useless because it cannot be referenced by any class
213                 new Object[] { "HiddenAnnotation", false },
214                 // class file with bad NestHost, NestMembers and InnerClasses or EnclosingMethod attribute
215                 // define them as nestmate to verify Class::getNestHost and getNestMembers
216                 new Object[] { "Outer", true },
217                 new Object[] { "Outer$Inner", true },
218                 new Object[] { "EnclosingClass", true },
219                 new Object[] { "EnclosingClass$1", true },
220         };
221     }
222 
223     /*
224      * Test that class file bytes that can be defined as a normal class
225      * can be successfully created as a hidden class even it might not
226      * make sense as a hidden class.  For example, a hidden annotation
227      * is not useful as it cannot be referenced and an outer/inner class
228      * when defined as a hidden effectively becomes a final top-level class.
229      */
230     @Test(dataProvider = "hiddenClasses")
231     public void defineHiddenClass(String name, boolean nestmate) throws Exception {
232         byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve(name + ".class"));
233         Class<?> hc;
234         Class<?> host;
235         if (nestmate) {
236             hc = lookup().defineHiddenClass(bytes, false, NESTMATE).lookupClass();
237             host = lookup().lookupClass().getNestHost();
238         } else {
239             hc = lookup().defineHiddenClass(bytes, false).lookupClass();
240             host = hc;
241         }
242         assertTrue(hc.getNestHost() == host);
243         assertTrue(hc.getNestMembers().length == 1);
244         assertTrue(hc.getNestMembers()[0] == host);
245     }
246 
247     @DataProvider(name = "emptyClasses")
248     private Object[][] emptyClasses() {
249         return new Object[][] {
250                 new Object[] { "EmptyHiddenSynthetic", ACC_SYNTHETIC | ACC_IDENTITY },
251                 new Object[] { "EmptyHiddenEnum", ACC_ENUM | ACC_IDENTITY },
252                 new Object[] { "EmptyHiddenAbstractClass", ACC_ABSTRACT | ACC_IDENTITY },
253                 new Object[] { "EmptyHiddenInterface", ACC_ABSTRACT|ACC_INTERFACE },
254                 new Object[] { "EmptyHiddenAnnotation", ACC_ANNOTATION|ACC_ABSTRACT|ACC_INTERFACE },
255         };
256     }
257 
258     /*
259      * Test if an empty class with valid access flags can be created as a hidden class
260      * as long as it does not violate the restriction of a hidden class.
261      *
262      * A meaningful enum type defines constants of that enum type.  So
263      * enum class containing constants of its type should not be a hidden
264      * class.
265      */
266     @Test(dataProvider = "emptyClasses")
267     public void emptyHiddenClass(String name, int accessFlags) throws Exception {
268         byte[] bytes = (accessFlags == (ACC_ENUM | ACC_IDENTITY)) ? classBytes(name, Enum.class, accessFlags)
269                                                  : classBytes(name, accessFlags);
270         Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
271         switch (accessFlags) {
272             case (ACC_SYNTHETIC | ACC_IDENTITY):
273                 assertTrue(hc.isSynthetic());
274                 assertFalse(hc.isEnum());
275                 assertFalse(hc.isAnnotation());
276                 assertFalse(hc.isInterface());
277                 break;
278             case (ACC_ENUM | ACC_IDENTITY):
279                 assertFalse(hc.isSynthetic());
280                 assertTrue(hc.isEnum());
281                 assertFalse(hc.isAnnotation());
282                 assertFalse(hc.isInterface());
283                 break;
284             case ACC_ABSTRACT | ACC_IDENTITY:
285                 assertFalse(hc.isSynthetic());
286                 assertFalse(hc.isEnum());
287                 assertFalse(hc.isAnnotation());
288                 assertFalse(hc.isInterface());
289                 break;
290             case ACC_ABSTRACT|ACC_INTERFACE:
291                 assertFalse(hc.isSynthetic());
292                 assertFalse(hc.isEnum());
293                 assertFalse(hc.isAnnotation());
294                 assertTrue(hc.isInterface());
295                 break;
296             case ACC_ANNOTATION|ACC_ABSTRACT|ACC_INTERFACE:
297                 assertFalse(hc.isSynthetic());
298                 assertFalse(hc.isEnum());
299                 assertTrue(hc.isAnnotation());
300                 assertTrue(hc.isInterface());
301                 break;
302             default:
303                 throw new IllegalArgumentException("unexpected access flag: " + accessFlags);
304         }
305         assertTrue(hc.isHidden());
306         assertEquals(hc.getModifiers(), (ACC_PUBLIC|accessFlags));
307         assertFalse(hc.isLocalClass());
308         assertFalse(hc.isMemberClass());
309         assertFalse(hc.isAnonymousClass());
310         assertFalse(hc.isArray());
311     }
312 
313     // These class files can't be defined as hidden classes
314     @DataProvider(name = "cantBeHiddenClasses")
315     private Object[][] cantBeHiddenClasses() {
316         return new Object[][] {
317                 // a hidden class can't be a field's declaring type
318                 // enum class with static final HiddenEnum[] $VALUES:
319                 new Object[] { "HiddenEnum" },
320                 // supertype of this class is a hidden class
321                 new Object[] { "HiddenSuper" },
322                 // a record class whose equals(HiddenRecord, Object) method
323                 // refers to a hidden class in the parameter type and fails
324                 // verification.  Perhaps this method signature should be reconsidered.
325                 new Object[] { "HiddenRecord" },
326         };
327     }
328 
329     /*
330      * These class files
331      */
332     @Test(dataProvider = "cantBeHiddenClasses", expectedExceptions = NoClassDefFoundError.class)
333     public void failToDeriveAsHiddenClass(String name) throws Exception {
334         byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve(name + ".class"));
335         Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
336     }
337 
338     /*
339      * A hidden class can be successfully created but fails to be reflected
340      * if it refers to its own type in the descriptor.
341      * e.g. Class::getMethods resolves the declaring type of fields,
342      * parameter types and return type.
343      */
344     @Test
345     public void hiddenCantReflect() throws Throwable {
346         HiddenTest t = (HiddenTest)defineHiddenClass("HiddenCantReflect").newInstance();
347         t.test();
348 
349         Class<?> c = t.getClass();
350         Class<?>[] intfs = c.getInterfaces();
351         assertTrue(intfs.length == 1);
352         assertTrue(intfs[0] == HiddenTest.class);
353 
354         try {
355             // this would cause loading of class HiddenCantReflect and NCDFE due
356             // to error during verification
357             c.getDeclaredMethods();
358         } catch (NoClassDefFoundError e) {
359             Throwable x = e.getCause();
360             if (x == null || !(x instanceof ClassNotFoundException && x.getMessage().contains("HiddenCantReflect"))) {
361                 throw e;
362             }
363         }
364     }
365 
366     @Test(expectedExceptions = { IllegalArgumentException.class })
367     public void cantDefineModule() throws Throwable {
368         Path src = Paths.get("module-info.java");
369         Path dir = CLASSES_DIR.resolve("m");
370         Files.write(src, List.of("module m {}"), StandardCharsets.UTF_8);
371         compileSources(src, dir);
372 
373         byte[] bytes = Files.readAllBytes(dir.resolve("module-info.class"));
374         lookup().defineHiddenClass(bytes, false);
375     }
376 
377     @Test(expectedExceptions = { IllegalArgumentException.class })
378     public void cantDefineClassInAnotherPackage() throws Throwable {
379         Path src = Paths.get("ClassInAnotherPackage.java");
380         Files.write(src, List.of("package p;", "public class ClassInAnotherPackage {}"), StandardCharsets.UTF_8);
381         compileSources(src, CLASSES_DIR);
382 
383         byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve("p").resolve("ClassInAnotherPackage.class"));
384         lookup().defineHiddenClass(bytes, false);
385     }
386 
387     @Test(expectedExceptions = { IllegalAccessException.class })
388     public void lessPrivilegedLookup() throws Throwable {
389         Lookup lookup = lookup().dropLookupMode(Lookup.PRIVATE);
390         lookup.defineHiddenClass(hiddenClassBytes, false);
391     }
392 
393     @Test(expectedExceptions = { UnsupportedClassVersionError.class })
394     public void badClassFileVersion() throws Throwable {
395         Path dir = Paths.get(System.getProperty("test.classes", "."));
396         byte[] bytes = Files.readAllBytes(dir.resolve("BadClassFileVersion.class"));
397         lookup().defineHiddenClass(bytes, false);
398     }
399 
400     // malformed class files
401     @DataProvider(name = "malformedClassFiles")
402     private Object[][] malformedClassFiles() throws IOException {
403         Path dir = Paths.get(System.getProperty("test.classes", "."));
404         return new Object[][] {
405                 // `this_class` has invalid CP entry
406                 new Object[] { Files.readAllBytes(dir.resolve("BadClassFile.class")) },
407                 new Object[] { Files.readAllBytes(dir.resolve("BadClassFile2.class")) },
408                 // truncated file
409                 new Object[] { new byte[0] },
410                 new Object[] { new byte[] {(byte) 0xCA, (byte) 0xBA, (byte) 0xBE, (byte) 0x00} },
411         };
412     }
413 
414     @Test(dataProvider = "malformedClassFiles", expectedExceptions = ClassFormatError.class)
415     public void badClassFile(byte[] bytes) throws Throwable {
416         lookup().defineHiddenClass(bytes, false);
417     }
418 
419     @DataProvider(name = "nestedTypesOrAnonymousClass")
420     private Object[][] nestedTypesOrAnonymousClass() {
421         return new Object[][] {
422                 // class file with bad InnerClasses or EnclosingMethod attribute
423                 new Object[] { "Outer", null },
424                 new Object[] { "Outer$Inner", "Outer" },
425                 new Object[] { "EnclosingClass", null },
426                 new Object[] { "EnclosingClass$1", "EnclosingClass" },
427         };
428     }
429 
430     @Test(dataProvider = "nestedTypesOrAnonymousClass")
431     public void hasInnerClassesOrEnclosingMethodAttribute(String className, String badDeclaringClassName) throws Throwable {
432         byte[] bytes = Files.readAllBytes(CLASSES_10_DIR.resolve(className + ".class"));
433         Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
434         hiddenClassWithBadAttribute(hc, badDeclaringClassName);
435     }
436 
437     // define a hidden class with static nest membership
438     @Test
439     public void hasStaticNestHost() throws Exception {
440         byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve("Outer$Inner.class"));
441         Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
442         hiddenClassWithBadAttribute(hc, "Outer");
443     }
444 
445     @Test
446     public void hasStaticNestMembers() throws Throwable {
447         byte[] bytes = Files.readAllBytes(CLASSES_DIR.resolve("Outer.class"));
448         Class<?> hc = lookup().defineHiddenClass(bytes, false).lookupClass();
449         assertHiddenClass(hc);
450         assertTrue(hc.getNestHost() == hc);
451         Class<?>[] members = hc.getNestMembers();
452         assertTrue(members.length == 1 && members[0] == hc);
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         assertTrue(hc.getCanonicalName() == null);
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             assertTrue(hc.getSimpleName().length() > 0);
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         assertTrue(hc.getNestHost() == hc);
474         // validate the static nest membership
475         Class<?>[] members = hc.getNestMembers();
476         assertTrue(members.length == 1 && members[0] == hc);
477     }
478 
479     // Class::getSimpleName, Class::isMemberClass
480     private void declaringClassNotFound(Class<?> c, String cn) {
481         try {
482             // fail to find declaring/enclosing class
483             c.isMemberClass();
484             assertTrue(false);
485         } catch (NoClassDefFoundError e) {
486             if (!e.getMessage().equals(cn)) {
487                 throw e;
488             }
489         }
490         try {
491             // fail to find declaring/enclosing class
492             c.getSimpleName();
493             assertTrue(false);
494         } catch (NoClassDefFoundError e) {
495             if (!e.getMessage().equals(cn)) {
496                 throw e;
497             }
498         }
499     }
500 
501     private static void singletonNest(Class<?> hc) {
502         assertTrue(hc.getNestHost() == hc);
503         assertTrue(hc.getNestMembers().length == 1);
504         assertTrue(hc.getNestMembers()[0] == hc);
505     }
506 
507     private static void assertHiddenClass(Class<?> hc) {
508         assertTrue(hc.isHidden());
509         assertTrue(hc.getCanonicalName() == null);
510         assertTrue(hc.getName().contains("/"));
511         assertFalse(hc.isAnonymousClass());
512         assertFalse(hc.isLocalClass());
513         assertFalse(hc.isMemberClass());
514         assertFalse(hc.getSimpleName().isEmpty()); // sanity check
515     }
516 
517     private static byte[] classBytes(String classname, int accessFlags) {
518         return classBytes(classname, Object.class, accessFlags);
519     }
520 
521     private static byte[] classBytes(String classname, Class<?> supertType, int accessFlags) {
522         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
523         cw.visit(V14, ACC_PUBLIC|accessFlags, classname, null, Type.getInternalName(supertType), null);
524         cw.visitEnd();
525 
526         return cw.toByteArray();
527     }
528 }