Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
useless duplicated code
[simgrid.git] / src / bindings / java / org / simgrid / NativeLib.java
1 /* Copyright (c) 2014. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 package org.simgrid;
8
9 import java.io.FileOutputStream;
10 import java.io.InputStream;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.File;
14 import java.nio.file.Files;
15 import java.nio.file.Path;
16
17 public final class NativeLib {
18         /* Statically load the library which contains all native functions used in here */
19         private static boolean isNativeInited = false;
20         static Path tempDir = null;
21
22         private NativeLib() {
23                 throw new IllegalAccessError("Utility class");
24         }
25
26         public static void nativeInit() {
27                 if (isNativeInited)
28                         return;
29
30                 if (System.getProperty("os.name").toLowerCase().startsWith("win"))
31                         NativeLib.nativeInit("winpthread-1");
32
33                 NativeLib.nativeInit("simgrid");
34                 NativeLib.nativeInit("simgrid-java");
35                 isNativeInited = true;
36         }
37
38         public static void nativeInit(String name) {
39                 try {
40                         /* Prefer the version of the library bundled into the jar file and use it */
41                         loadLib(name);
42                 } catch (LinkageException embeededException) {
43                         /* If not found, try to see if we can find a version on disk */
44                         try {
45                                 System.loadLibrary(name);
46                         } catch (UnsatisfiedLinkError systemException) {
47                                 if (! "boost_context".equals(name)) { // Ignore when we cannot load boost_context
48                                         
49                                         System.err.println("\nCannot load the bindings to the "+name+" library in path "+getPath());
50                                         Throwable cause = embeededException.getCause();
51                                         if (cause instanceof java.lang.UnsatisfiedLinkError) {
52                                                 if (cause.getMessage().matches(".*libcgraph.so.*"))
53                                                         System.err.println("HINT: Try to install the libcgraph package (sudo apt-get install libcgraph).");
54                                                 else if (cause.getMessage().matches(".*libboost_context.so.*"))
55                                                         System.err.println("HINT: Try to install the boost-context package (sudo apt-get install libboost-context-dev).");
56                                                 else
57                                                         System.err.println("Try to install the missing dependencies, which name should appear above.");
58                                         } else {
59                                                 System.err.println("This jar file does not seem to fit your system, and no usable SimGrid installation found on disk.");
60                                         }
61                                         System.err.println();
62                                         cause.printStackTrace();
63                                         System.exit(1);
64                                 }
65                         }
66                 }
67         }
68
69         public static String getPath() {
70                 // Inspiration: https://github.com/xerial/snappy-java/blob/develop/src/main/java/org/xerial/snappy/OSInfo.java
71                 String prefix = "NATIVE";
72                 String os = System.getProperty("os.name");
73                 String arch = System.getProperty("os.arch");
74
75                 if (arch.matches("^i[3-6]86$"))
76                         arch = "x86";
77                 else if ("x86_64".equalsIgnoreCase(arch) || "AMD64".equalsIgnoreCase(arch))
78                         arch = "amd64";
79
80                 if (os.toLowerCase().startsWith("win")){
81                         os = "Windows";
82                 } else if (os.contains("OS X"))
83                         os = "Darwin";
84
85                 os = os.replace(' ', '_');
86                 arch = arch.replace(' ', '_');
87
88                 return prefix + "/" + os + "/" + arch + "/";
89         }
90
91         private static void loadLib (String name) throws LinkageException {
92                 String path = NativeLib.getPath();
93
94                 String filename=name;
95                 InputStream in = NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
96
97                 if (in == null) {
98                         filename = "lib"+name+".so";
99                         in = NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
100                 }
101                 if (in == null) {
102                         filename = name+".dll";
103                         in =  NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
104                 }
105                 if (in == null) {
106                         filename = "lib"+name+".dll";
107                         in =  NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
108                 }
109                 if (in == null) {
110                         filename = "lib"+name+".dylib";
111                         in =  NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
112                 }
113                 if (in == null) {
114                         throw new LinkageException("Cannot find library "+name+" in path "+path+". Sorry, but this jar does not seem to be usable on your machine.");
115                 }
116                 try {
117                         // We must write the lib onto the disk before loading it -- stupid operating systems
118                         if (tempDir == null) {
119                                 tempDir = Files.createTempDirectory("simgrid-java-");
120                                 // don't leak the files on disk, but remove it on JVM shutdown
121                                 Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(tempDir.toFile())));
122                         }
123                         File fileOut = new File(tempDir.toFile().getAbsolutePath() + File.separator + filename);
124
125                         /* copy the library in position */  
126                         OutputStream out = new FileOutputStream(fileOut);
127                         byte[] buffer = new byte[4096]; 
128                         int bytesRead; 
129                         while ((bytesRead = in.read(buffer)) != -1)     // Read until EOF
130                                 out.write(buffer, 0, bytesRead); 
131
132                         /* close all file descriptors, and load that shit */
133                         in.close();
134                         out.close();
135                         System.load(fileOut.getAbsolutePath());
136                 } catch (SecurityException|UnsatisfiedLinkError|IOException e) {
137                         throw new LinkageException("Cannot load the bindings to the "+name+" library in path "+getPath(), e);
138                 }
139         }
140
141         /* A hackish mechanism used to remove the file containing our library when the JVM shuts down */
142         private static class FileCleaner implements Runnable {
143                 private File dir;
144                 public FileCleaner(File dir) {
145                         this.dir = dir;
146                 }
147                 @Override
148                 public void run() {
149                         try {
150                                 for (File f : dir.listFiles())
151                                         if (! f.delete() )
152                                                 System.err.println("Unable to clean temporary file "+f.getAbsolutePath()+" during shutdown.");
153                                 if (! dir.delete() )
154                                         System.err.println("Unable to clean temporary file "+dir.getAbsolutePath()+" during shutdown.");                                
155                         } catch(Exception e) {
156                                 System.err.println("Unable to clean temporary file "+dir.getAbsolutePath()+" during shutdown: "+e.getCause());
157                                 e.printStackTrace();
158                         }
159                 }
160         }
161
162
163         public static void main(String[] args) {
164                 System.out.println("This jarfile searches the native code under: " +getPath());
165         }
166 }
167
168 class LinkageException extends Exception {
169         private static final long serialVersionUID = 1L;
170         public LinkageException(String msg) {
171                 super(msg);
172         }
173
174         public LinkageException(String msg, Throwable e) {
175                 super(msg,e);
176         }
177 }