1 /*
  2  * Copyright (c) 2023, 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 import java.lang.classfile.ClassFile;
 25 import jdk.test.lib.util.ForceGC;
 26 import org.junit.jupiter.api.Test;
 27 import org.junit.jupiter.params.ParameterizedTest;
 28 import org.junit.jupiter.params.provider.ValueSource;
 29 
 30 import java.lang.constant.ClassDesc;
 31 import java.lang.constant.MethodTypeDesc;
 32 import java.lang.invoke.MethodHandle;
 33 import java.lang.invoke.MethodHandleProxies;
 34 import java.lang.invoke.MethodHandles;
 35 import java.lang.invoke.MethodType;
 36 import java.lang.ref.WeakReference;
 37 import java.util.Comparator;
 38 
 39 import static java.lang.constant.ConstantDescs.*;
 40 import static java.lang.invoke.MethodHandleProxies.*;
 41 import static java.lang.invoke.MethodType.methodType;
 42 import static java.lang.classfile.ClassFile.*;
 43 import static org.junit.jupiter.api.Assertions.*;
 44 
 45 /*
 46  * @test
 47  * @bug 6983726
 48  * @library /test/lib
 49  * @enablePreview
 50  * @summary Tests on implementation hidden classes spinned by MethodHandleProxies
 51  * @build WrapperHiddenClassTest Client jdk.test.lib.util.ForceGC
 52  * @run junit WrapperHiddenClassTest
 53  */
 54 public class WrapperHiddenClassTest {
 55 
 56     /**
 57      * Tests an adversary "implementation" class will not be
 58      * "recovered" by the wrapperInstance* APIs
 59      */
 60     @Test
 61     public void testWrapperInstance() throws Throwable {
 62         Comparator<Integer> hostile = createHostileInstance();
 63         var mh = MethodHandles.publicLookup()
 64                 .findVirtual(Integer.class, "compareTo", methodType(int.class, Integer.class));
 65         @SuppressWarnings("unchecked")
 66         Comparator<Integer> proxy = (Comparator<Integer>) asInterfaceInstance(Comparator.class, mh);
 67 
 68         assertTrue(isWrapperInstance(proxy));
 69         assertFalse(isWrapperInstance(hostile));
 70         assertSame(mh, wrapperInstanceTarget(proxy));
 71         assertThrows(IllegalArgumentException.class, () -> wrapperInstanceTarget(hostile));
 72         assertSame(Comparator.class, wrapperInstanceType(proxy));
 73         assertThrows(IllegalArgumentException.class, () -> wrapperInstanceType(hostile));
 74     }
 75 
 76     private static final String TYPE = "interfaceType";
 77     private static final String TARGET = "target";
 78     private static final ClassDesc CD_HostileWrapper = ClassDesc.of("HostileWrapper");
 79     private static final ClassDesc CD_Comparator = ClassDesc.of("java.util.Comparator");
 80     private static final MethodTypeDesc MTD_int_Object_Object = MethodTypeDesc.of(CD_int, CD_Object, CD_Object);
 81     private static final MethodTypeDesc MTD_int_Integer = MethodTypeDesc.of(CD_int, CD_Integer);
 82 
 83     // Update this template when the MHP template is updated
 84     @SuppressWarnings("unchecked")
 85     private Comparator<Integer> createHostileInstance() throws Throwable {
 86         var cf = ClassFile.of();
 87         var bytes = cf.build(CD_HostileWrapper, clb -> {
 88             clb.withSuperclass(CD_Object);
 89             clb.withFlags(ACC_FINAL | ACC_SYNTHETIC);
 90             clb.withInterfaceSymbols(CD_Comparator);
 91 
 92             // static and instance fields
 93             clb.withField(TYPE, CD_Class, ACC_PRIVATE | ACC_STATIC | ACC_FINAL);
 94             clb.withField(TARGET, CD_MethodHandle, ACC_PRIVATE | ACC_FINAL);
 95 
 96             // <clinit>
 97             clb.withMethodBody(CLASS_INIT_NAME, MTD_void, ACC_STATIC, cob -> {
 98                 cob.loadConstant(CD_Comparator);
 99                 cob.putstatic(CD_HostileWrapper, TYPE, CD_Class);
100                 cob.return_();
101             });
102 
103             // <init>
104             clb.withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, cob -> {
105                 cob.aload(0);
106                 cob.invokespecial(CD_Object, INIT_NAME, MTD_void);
107                 cob.return_();
108             });
109 
110             // implementation
111             clb.withMethodBody("compare", MTD_int_Object_Object, ACC_PUBLIC, cob -> {
112                 cob.aload(1);
113                 cob.checkcast(CD_Integer);
114                 cob.aload(2);
115                 cob.checkcast(CD_Integer);
116                 cob.invokestatic(CD_Integer, "compareTo", MTD_int_Integer);
117                 cob.ireturn();
118             });
119         });
120         var l = MethodHandles.lookup().defineHiddenClass(bytes, true);
121         return (Comparator<Integer>) l.findConstructor(l.lookupClass(), MethodType.methodType(void.class)).invoke();
122     }
123 
124     /**
125      * Ensures a user interface cannot access a Proxy implementing it.
126      */
127     @Test
128     public void testNoAccess() {
129         var instance = asInterfaceInstance(Client.class, MethodHandles.zero(void.class));
130         var instanceClass = instance.getClass();
131         var interfaceLookup = Client.lookup();
132         assertEquals(MethodHandles.Lookup.ORIGINAL, interfaceLookup.lookupModes() & MethodHandles.Lookup.ORIGINAL,
133                 "Missing original flag on interface's lookup");
134         assertThrows(IllegalAccessException.class, () -> MethodHandles.privateLookupIn(instanceClass,
135                 interfaceLookup));
136     }
137 
138     /**
139      * Tests the Proxy module properties for Proxies implementing system and
140      * user interfaces.
141      */
142     @ParameterizedTest
143     @ValueSource(classes = {Client.class, Runnable.class})
144     public void testModule(Class<?> ifaceClass) {
145         var mh = MethodHandles.zero(void.class);
146 
147         var inst = asInterfaceInstance(ifaceClass, mh);
148         Module ifaceModule = ifaceClass.getModule();
149         Class<?> implClass = inst.getClass();
150         Module implModule = implClass.getModule();
151 
152         String implPackage = implClass.getPackageName();
153         assertFalse(implModule.isExported(implPackage),
154                 "implementation should not be exported");
155         assertTrue(ifaceModule.isExported(ifaceClass.getPackageName(), implModule),
156                 "interface package should be exported to implementation");
157         assertTrue(implModule.isOpen(implPackage, MethodHandleProxies.class.getModule()),
158                 "implementation class is not reflectively open to MHP class");
159         assertTrue(implModule.isNamed(), "dynamic module must be named");
160         assertTrue(implModule.getName().startsWith("jdk.MHProxy"),
161                 () -> "incorrect dynamic module name: " + implModule.getName());
162 
163         assertSame(ifaceClass.getClassLoader(), implClass.getClassLoader(),
164                 "wrapper class should use the interface's loader ");
165         assertSame(implClass.getClassLoader(), implModule.getClassLoader(),
166                 "module class loader should be wrapper class's loader");
167     }
168 
169     /**
170      * Tests the access control of Proxies implementing system and user
171      * interfaces.
172      */
173     @ParameterizedTest
174     @ValueSource(classes = {Client.class, Runnable.class})
175     public void testNoInstantiation(Class<?> ifaceClass) throws ReflectiveOperationException {
176         var mh = MethodHandles.zero(void.class);
177         var instanceClass = asInterfaceInstance(ifaceClass, mh).getClass();
178         var ctor = instanceClass.getDeclaredConstructor(MethodHandles.Lookup.class, MethodHandle.class, MethodHandle.class);
179 
180         assertThrows(IllegalAccessException.class, () -> ctor.newInstance(Client.lookup(), mh, mh));
181         assertThrows(IllegalAccessException.class, () -> ctor.newInstance(MethodHandles.lookup(), mh, mh));
182         assertThrows(IllegalAccessException.class, () -> ctor.newInstance(MethodHandles.publicLookup(), mh, mh));
183     }
184 
185     /**
186      * Tests the caching and weak reference of implementation classes for
187      * system and user interfaces.
188      */
189     @ParameterizedTest
190     @ValueSource(classes = {Runnable.class, Client.class})
191     public void testWeakImplClass(Class<?> ifaceClass) {
192         var mh = MethodHandles.zero(void.class);
193 
194         var wrapper1 = asInterfaceInstance(ifaceClass, mh);
195         var implClass = wrapper1.getClass();
196 
197         System.gc(); // helps debug if incorrect items are weakly referenced
198         var wrapper2 = asInterfaceInstance(ifaceClass, mh);
199         assertSame(implClass, wrapper2.getClass(),
200                 "MHP should reuse old implementation class when available");
201 
202         var implClassRef = new WeakReference<>(implClass);
203         // clear strong references
204         implClass = null;
205         wrapper1 = null;
206         wrapper2 = null;
207 
208         if (!ForceGC.wait(() -> implClassRef.refersTo(null))) {
209             fail("MHP impl class cannot be cleared by GC");
210         }
211     }
212 }