1 /* 2 * Copyright (c) 2021, 2022, 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 * @enablePreview 27 * @requires jdk.foreign.linker != "UNSUPPORTED" 28 * @compile lookup/Lookup.java 29 * @compile invoker/Invoker.java 30 * @run main/othervm --enable-native-access=ALL-UNNAMED TestLoaderLookup 31 */ 32 33 import java.lang.foreign.*; 34 import java.lang.reflect.*; 35 import java.net.MalformedURLException; 36 import java.net.URL; 37 import java.net.URLClassLoader; 38 import java.nio.file.Paths; 39 40 public class TestLoaderLookup { 41 public static void main(String[] args) throws ReflectiveOperationException { 42 ClassLoader loader1 = newClassLoader("lookup"); 43 Class<?> lookup = loader1.loadClass("lookup.Lookup"); 44 Method fooSymbol = lookup.getDeclaredMethod("fooSymbol"); 45 MemorySegment foo = (MemorySegment) fooSymbol.invoke(null); 46 47 ClassLoader loader2 = newClassLoader("invoker"); 48 Class<?> invoker = loader2.loadClass("invoker.Invoker"); 49 Method invoke = invoker.getDeclaredMethod("invoke", MemorySegment.class); 50 invoke.invoke(null, foo); 51 52 loader1 = null; 53 lookup = null; 54 fooSymbol = null; 55 // Make sure that the loader is kept reachable 56 for (int i = 0 ; i < 1000 ; i++) { 57 invoke.invoke(null, foo); // might crash if loader1 is GC'ed 58 System.gc(); 59 } 60 } 61 62 public static ClassLoader newClassLoader(String path) { 63 try { 64 return new URLClassLoader(new URL[] { 65 Paths.get(System.getProperty("test.classes", path)).toUri().toURL(), 66 }, null); 67 } catch (MalformedURLException e){ 68 throw new RuntimeException("Unexpected URL conversion failure", e); 69 } 70 } 71 }