Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
[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))
78                         arch = "amd64";
79                 else if ("AMD64".equalsIgnoreCase(arch))
80                         arch = "amd64";
81
82                 if (os.toLowerCase().startsWith("win")){
83                         os = "Windows";
84                 } else if (os.contains("OS X"))
85                         os = "Darwin";
86
87                 os = os.replace(' ', '_');
88                 arch = arch.replace(' ', '_');
89
90                 return prefix + "/" + os + "/" + arch + "/";
91         }
92
93         private static void loadLib (String name) throws LinkageException {
94                 String path = NativeLib.getPath();
95
96                 String filename=name;
97                 InputStream in = NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
98
99                 if (in == null) {
100                         filename = "lib"+name+".so";
101                         in = NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
102                 }
103                 if (in == null) {
104                         filename = name+".dll";
105                         in =  NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
106                 }
107                 if (in == null) {
108                         filename = "lib"+name+".dll";
109                         in =  NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
110                 }
111                 if (in == null) {
112                         filename = "lib"+name+".dylib";
113                         in =  NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
114                 }
115                 if (in == null) {
116                         throw new LinkageException("Cannot find library "+name+" in path "+path+". Sorry, but this jar does not seem to be usable on your machine.");
117                 }
118                 try {
119                         // We must write the lib onto the disk before loading it -- stupid operating systems
120                         if (tempDir == null) {
121                                 tempDir = Files.createTempDirectory("simgrid-java-");
122                                 // don't leak the files on disk, but remove it on JVM shutdown
123                                 Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(tempDir.toFile())));
124                         }
125                         File fileOut = new File(tempDir.toFile().getAbsolutePath() + File.separator + filename);
126
127                         /* copy the library in position */  
128                         OutputStream out = new FileOutputStream(fileOut);
129                         byte[] buffer = new byte[4096]; 
130                         int bytesRead; 
131                         while ((bytesRead = in.read(buffer)) != -1)     // Read until EOF
132                                 out.write(buffer, 0, bytesRead); 
133
134                         /* close all file descriptors, and load that shit */
135                         in.close();
136                         out.close();
137                         System.load(fileOut.getAbsolutePath());
138                 } catch (SecurityException|UnsatisfiedLinkError|IOException e) {
139                         throw new LinkageException("Cannot load the bindings to the "+name+" library in path "+getPath(), e);
140                 }
141         }
142
143         /* A hackish mechanism used to remove the file containing our library when the JVM shuts down */
144         private static class FileCleaner implements Runnable {
145                 private File dir;
146                 public FileCleaner(File dir) {
147                         this.dir = dir;
148                 }
149                 @Override
150                 public void run() {
151                         try {
152                                 for (File f : dir.listFiles())
153                                         if (! f.delete() )
154                                                 System.err.println("Unable to clean temporary file "+f.getAbsolutePath()+" during shutdown.");
155                                 if (! dir.delete() )
156                                         System.err.println("Unable to clean temporary file "+dir.getAbsolutePath()+" during shutdown.");                                
157                         } catch(Exception e) {
158                                 System.err.println("Unable to clean temporary file "+dir.getAbsolutePath()+" during shutdown: "+e.getCause());
159                                 e.printStackTrace();
160                         }
161                 }
162         }
163
164
165         public static void main(String[] args) {
166                 System.out.println("This jarfile searches the native code under: " +getPath());
167         }
168 }
169
170 class LinkageException extends Exception {
171         private static final long serialVersionUID = 1L;
172         public LinkageException(String msg) {
173                 super(msg);
174         }
175
176         public LinkageException(String msg, Throwable e) {
177                 super(msg,e);
178         }
179 }