Logo AND Algorithmique Numérique Distribuée

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