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