Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
757b8efa2a3490091644c929a9f2e837a4a36863
[simgrid.git] / src / bindings / java / org / simgrid / NativeLib.java
1 /* Copyright (c) 2014-2019. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 package org.simgrid;
7
8 import java.io.FileOutputStream;
9 import java.io.InputStream;
10 import java.io.IOException;
11 import java.io.OutputStream;
12 import java.io.File;
13 import java.nio.file.Files;
14 import java.nio.file.Path;
15 import java.util.stream.Stream;
16
17 /** Helper class loading the native functions of SimGrid that we use for downcalls
18  *
19  * Almost all org.simgrid.msg.* classes contain a static bloc (thus executed when the class is loaded)
20  * containing a call to this.
21  */
22 public final class NativeLib {
23         private static boolean isNativeInited = false;
24         private static Path tempDir = null; // where the embeeded libraries are unpacked before loading them
25
26         /** A static-only "class" don't need no constructor */
27         private NativeLib() {
28                 throw new IllegalAccessError("Utility class");
29         }
30
31         /** Hidden debug main() function
32          *
33          * It is not the Main-Class defined in src/bindings/java/MANIFEST.in (org.simgrid.msg.Msg is),
34          * so it won't get executed by default. But that's helpful to debug linkage errors, if you
35          * know that it exists. It's used by cmake during the configure, to inform the user.
36          */
37         public static void main(String[] args) {
38                 System.out.println("This jarfile searches the native code under: " +getPath());
39         }
40         
41         /** Main function loading all the native classes that we need */
42         public static void nativeInit() {
43                 if (isNativeInited)
44                         return;
45
46                 if (System.getProperty("os.name").toLowerCase().startsWith("win"))
47                         NativeLib.nativeInit("winpthread-1");
48
49                 NativeLib.nativeInit("simgrid");
50                 NativeLib.nativeInit("simgrid-java");
51                 isNativeInited = true;
52         }
53
54         /** Helper function trying to load one requested library */
55         public static void nativeInit(String name) {
56                 Throwable cause = null;
57                 try {
58                         /* Prefer the version of the library bundled into the jar file and use it */
59                         if (loadLibAsStream(name))
60                                 return;
61                 } catch (UnsatisfiedLinkError|SecurityException|IOException e) {
62                         cause = e;
63                 }
64                 
65                 /* If not found, try to see if we can find a version on disk */
66                 try {
67                         System.loadLibrary(name);
68                         return;
69                 } catch (UnsatisfiedLinkError systemException) { /* don't care */ }
70                 
71                 System.err.println("\nCannot load the bindings to the "+name+" library in path "+getPath()+" and no usable SimGrid installation found on disk.");
72                 if (cause != null) {
73                         if (cause.getMessage().contains("libcgraph.so"))
74                                 System.err.println("HINT: Try to install the libcgraph package (sudo apt-get install libcgraph).");
75                         else if (cause.getMessage().contains("libboost_context.so"))
76                                 System.err.println("HINT: Try to install the boost-context package (sudo apt-get install libboost-context-dev).");
77                         else
78                                 System.err.println("Try to install the missing dependencies, if any. Read carefully the following error message.");
79
80                         System.err.println();
81                         cause.printStackTrace();
82                 } else {
83                         System.err.println("This jar file does not seem to fit your system, and no usable SimGrid installation found on disk for "+name+".");
84                 }
85                 System.exit(1);
86         }
87
88         /** Try to extract the library from the jarfile before loading it */
89         private static boolean loadLibAsStream (String name) throws IOException, UnsatisfiedLinkError {
90                 String path = NativeLib.getPath();
91                 
92                 // We must write the lib onto the disk before loading it -- stupid operating systems
93                 if (tempDir == null) {
94
95                         if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
96                                 // The cleanup at exit fails on Windows where it is impossible to delete files which are still in
97                                 // use.  Try to remove stale temporary files from previous executions, and limit disk usage.
98                                 Path tmpdir = (new File(System.getProperty("java.io.tmpdir"))).toPath();
99                                 Files.find(tmpdir, 1, (Path p, java.nio.file.attribute.BasicFileAttributes a) ->
100                                            a.isDirectory() && !p.equals(tmpdir) &&
101                                            p.getFileName().toString().startsWith("simgrid-java-"))
102                                      .map(Path::toFile)
103                                      .map(FileCleaner::new)
104                                      .forEach(FileCleaner::run);
105                         }
106
107                         tempDir = Files.createTempDirectory("simgrid-java-");
108                         // don't leak the files on disk, but remove it on JVM shutdown
109                         Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(tempDir.toFile())));
110                 }
111                 
112                 /* For each possible filename of the given library on all possible OSes, try it */
113                 for (String filename : new String[]
114                    { name,
115                      "lib"+name+".so",               /* linux */
116                      name+".dll", "lib"+name+".dll", /* windows (pure and mingw) */
117                      "lib"+name+".dylib"             /* macOS */}) {
118                                                 
119                         File fileOut = new File(tempDir.toFile(), filename);
120                         try ( // Try-with-resources. These stream will be autoclosed when needed.
121                                 InputStream in = NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
122                         ) {
123                                 if (in != null) {
124                                         /* copy the library in position */
125                                         Files.copy(in, fileOut.toPath());
126
127                                         /* load that library */
128                                         System.load(fileOut.getAbsolutePath());
129
130                                         /* It loaded! we're good */
131                                         return true;
132                                 }
133                         }
134                 }
135                 
136                 /* No suitable name found */
137                 return false;
138         }
139
140         /** Find where to search for the library in the jar -- keep it aligned with where cmake puts it! */
141         private static String getPath() {
142                 // Inspiration: https://github.com/xerial/snappy-java/blob/develop/src/main/java/org/xerial/snappy/OSInfo.java
143                 String prefix = "NATIVE";
144                 String os = System.getProperty("os.name");
145                 String arch = System.getProperty("os.arch");
146
147                 if (arch.matches("^i[3-6]86$"))
148                         arch = "x86";
149                 else if ("x86_64".equalsIgnoreCase(arch) || "AMD64".equalsIgnoreCase(arch))
150                         arch = "amd64";
151
152                 if (os.toLowerCase().startsWith("win")) {
153                         os = "Windows";
154                 } else if (os.contains("OS X")) {
155                         os = "Darwin";
156                 }
157                 os = os.replace(' ', '_');
158                 arch = arch.replace(' ', '_');
159
160                 return prefix + "/" + os + "/" + arch + "/";
161         }
162         
163         /** A hackish mechanism used to remove the file containing our library when the JVM shuts down */
164         private static class FileCleaner implements Runnable {
165                 private File dir;
166                 public FileCleaner(File dir) {
167                         this.dir = dir;
168                 }
169                 @Override
170                 public void run() {
171                         try (Stream<Path> paths = Files.walk(dir.toPath())) {
172                                 paths.sorted(java.util.Comparator.reverseOrder())
173                                      .map(java.nio.file.Path::toFile)
174                                      //.peek(System.err::println) // Prints what gets removed
175                                      .forEach(java.io.File::delete);
176                         } catch(Exception e) {
177                                 System.err.println("Error while cleaning temporary file " + dir.getAbsolutePath() +
178                                                    ": " + e.getCause());
179                                 e.printStackTrace();
180                         }
181                 }
182         }
183 }