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