Logo AND Algorithmique Numérique Distribuée

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