1 /* 2 * Copyright (c) 2016, 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 package jdk.internal.nicl; 24 25 import jdk.internal.misc.JavaLangAccess; 26 import jdk.internal.misc.SharedSecrets; 27 import jdk.internal.org.objectweb.asm.Type; 28 29 import java.lang.invoke.MethodHandles.Lookup; 30 import java.nicl.Library; 31 import java.nicl.Libraries; 32 import java.nicl.metadata.NativeHeader; 33 import java.nicl.metadata.NativeType; 34 import java.nio.file.Files; 35 import java.nio.file.Path; 36 import java.nio.file.Paths; 37 import java.util.Arrays; 38 import java.util.Map; 39 import java.util.WeakHashMap; 40 import java.util.Optional; 41 import java.security.AccessController; 42 import java.security.PrivilegedAction; 43 44 public final class LibrariesHelper { 45 private LibrariesHelper() {} 46 47 private static final JavaLangAccess jlAccess = SharedSecrets.getJavaLangAccess(); 48 49 private static String generateImplName(Class<?> c) { 50 return Type.getInternalName(c) + "$" + "Impl"; 51 } 52 53 /** 54 * Generate the implementation for an interface. 55 * 56 * @param c the interface for which to return an implementation class 57 * @param generator a generator capable of generating an implementation, if needed 58 * @return a class implementing the interface 59 */ 60 private static Class<?> generateImpl(Class<?> c, BinderClassGenerator generator) { 61 try { 62 return AccessController.doPrivileged((PrivilegedAction<Class<?>>) () -> { 63 return generator.generate(); 64 }); 65 } catch (Exception e) { 66 throw new RuntimeException("Failed to generate implementation for class " + c, e); 67 } 68 } 69 70 // Cache: Struct interface Class -> Impl Class. 71 private static final ClassValue<Class<?>> STRUCT_IMPLEMENTATIONS = new ClassValue<>() { 72 @Override 73 protected Class<?> computeValue(Class<?> c) { 74 assert c.isAnnotationPresent(NativeType.class) && 75 c.getAnnotation(NativeType.class).isRecordType(); 76 return generateImpl(c, new StructImplGenerator(c, generateImplName(c), c)); 77 } 78 }; 79 80 /** 81 * Get the implementation for a Struct interface. 82 * 83 * @param c the Struct interface for which to return an implementation class 84 * @return a class implementing the interface 85 */ 86 @SuppressWarnings("unchecked") 87 public static <T> Class<? extends T> getStructImplClass(Class<T> c) { 88 boolean isRecordType = c.isAnnotationPresent(NativeType.class) && 89 c.getAnnotation(NativeType.class).isRecordType(); 90 if (! isRecordType) { 91 throw new IllegalArgumentException("Not a Struct interface: " + c); 92 } 93 94 return (Class<? extends T>)STRUCT_IMPLEMENTATIONS.get(c); 95 } 96 97 // This is used to pass the current SymbolLookup object to the header computeValue method below. 98 private static final ThreadLocal<SymbolLookup> curSymLookup = new ThreadLocal<>(); 99 100 // Cache: Header interface Class -> Impl Class. 101 private static final ClassValue<Class<?>> HEADER_IMPLEMENTATIONS = new ClassValue<>() { 102 @Override 103 protected Class<?> computeValue(Class<?> c) { 104 assert c.isAnnotationPresent(NativeHeader.class); 105 assert curSymLookup.get() != null; 106 String implName = generateImplName(c); 107 BinderClassGenerator generator = new HeaderImplGenerator(c, implName, c, curSymLookup.get()); 108 return generateImpl(c, generator); 109 } 110 }; 111 112 /** 113 * Get an implementation class for a header type 114 * 115 * @param c an interface representing a header file - must have an @NativeHeader annotation 116 * @param lookup the symbol lookup to use to look up native symbols 117 * @return a class implementing the header 118 */ 119 @SuppressWarnings("unchecked") 120 private static <T> Class<? extends T> getHeaderImplClass(Class<T> c, SymbolLookup lookup) { 121 if (!c.isAnnotationPresent(NativeHeader.class)) { 122 throw new IllegalArgumentException("No @NativeHeader annotation on class " + c); 123 } 124 125 // Thread local is used to pass additional argument to the header 126 // implementation generator's computeValue method. 127 try { 128 curSymLookup.set(lookup); 129 return (Class<? extends T>)HEADER_IMPLEMENTATIONS.get(c); 130 } finally { 131 curSymLookup.remove(); 132 } 133 } 134 135 /** 136 * Load the specified shared library. 137 * 138 * @param lookup Lookup object of the caller. 139 * @param name Name of the shared library to load. 140 */ 141 public static Library loadLibrary(Lookup lookup, String name) { 142 return jlAccess.findLibrary(lookup, name); 143 } 144 145 // return the absolute path of the library of given name by searching 146 // in the given array of paths. 147 private static Optional<Path> findLibraryPath(Path[] paths, String libName) { 148 return Arrays.stream(paths). 149 map(p -> p.resolve(System.mapLibraryName(libName))). 150 filter(Files::isRegularFile).map(Path::toAbsolutePath).findFirst(); 151 } 152 153 /** 154 * Load the specified shared libraries from the specified paths. 155 * 156 * @param lookup Lookup object of the caller. 157 * @param pathStrs array of paths to load the shared libraries from. 158 * @param names array of shared library names. 159 */ 160 // used by jextract tool to load libraries for symbol checks. 161 public static Library[] loadLibraries(Lookup lookup, String[] pathStrs, String[] names) { 162 if (pathStrs == null || pathStrs.length == 0) { 163 return Arrays.stream(names).map( 164 name -> Libraries.loadLibrary(lookup, name)).toArray(Library[]::new); 165 } else { 166 Path[] paths = Arrays.stream(pathStrs).map(Paths::get).toArray(Path[]::new); 167 return Arrays.stream(names).map(libName -> { 168 Optional<Path> absPath = findLibraryPath(paths, libName); 169 return absPath.isPresent() ? 170 Libraries.load(lookup, absPath.get().toString()) : 171 Libraries.loadLibrary(lookup, libName); 172 }).toArray(Library[]::new); 173 } 174 } 175 176 private static Library[] loadLibraries(Lookup lookup, NativeHeader nativeHeader) { 177 return loadLibraries(lookup, nativeHeader.libraryPaths(), nativeHeader.libraries()); 178 } 179 180 private static SymbolLookup getSymbolLookupForClass(Lookup lookup, Class<?> c) { 181 NativeHeader nativeHeader = c.getAnnotation(NativeHeader.class); 182 Library[] libs = nativeHeader == null || nativeHeader.libraries().length == 0 ? 183 new Library[] { getDefaultLibrary() } : 184 loadLibraries(lookup, nativeHeader); 185 186 return new SymbolLookup(libs); 187 } 188 189 public static Library getDefaultLibrary() { 190 return jlAccess.defaultLibrary(); 191 } 192 193 /** 194 * Create a raw, uncivilized version of the interface 195 * 196 * @param c the interface class to bind 197 * @param lib the library in which to look for native symbols 198 * @return an object of class implementing the interfacce 199 */ 200 public static <T> T bind(Class<T> c, Library lib) { 201 return bind(c, new SymbolLookup(lib)); 202 } 203 204 private static <T> T bind(Class<T> c, SymbolLookup lookup) { 205 Class<? extends T> cls = getHeaderImplClass(c, lookup); 206 207 try { 208 @SuppressWarnings("unchecked") 209 T instance = (T) cls.getDeclaredConstructor().newInstance(); 210 return instance; 211 } catch (ReflectiveOperationException e) { 212 throw new Error(e); 213 } 214 } 215 216 /** 217 * Create a raw, uncivilized version of the interface 218 * 219 * @param lookup the lookup object (used for implicit native library lookup) 220 * @param c the class to bind 221 * @return an object of class implementing the interfacce 222 */ 223 public static <T> T bind(Lookup lookup, Class<T> c) { 224 return bind(c, getSymbolLookupForClass(lookup, c)); 225 } 226 } --- EOF ---