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