Logo AND Algorithmique Numérique Distribuée

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