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