Logo AND Algorithmique Numérique Distribuée

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