1 /* Copyright (c) 2014-2022. The SimGrid Team. All rights reserved. */
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. */
8 import java.io.InputStream;
9 import java.io.IOException;
11 import java.nio.file.Files;
12 import java.nio.file.Path;
13 import java.util.stream.Stream;
15 /** Helper class loading the native functions of SimGrid that we use for downcalls
17 * Almost all org.simgrid.msg.* classes contain a static block (thus executed when the class is loaded)
18 * containing a call to this.
20 public final class NativeLib {
21 private static final boolean WINDOWS_OS = System.getProperty("os.name").toLowerCase().startsWith("win");
22 private static boolean isNativeInited = false;
23 private static Path tempDir = null; // where the embeeded libraries are unpacked before loading them
25 /** A static-only "class" don't need no constructor */
27 throw new IllegalAccessError("Utility class");
30 /** Hidden debug main() function
32 * It is not the Main-Class defined in src/bindings/java/MANIFEST.in (org.simgrid.msg.Msg is),
33 * so it won't get executed by default. But that's helpful to debug linkage errors, if you
34 * know that it exists. It's used by cmake during the configure, to inform the user.
36 public static void main(String[] args) {
37 System.out.println("This jarfile searches the native code under: " +getPath());
40 /** Main function loading all the native classes that we need */
41 public static void nativeInit() {
46 NativeLib.nativeInit("winpthread-1");
48 NativeLib.nativeInit("simgrid");
49 NativeLib.nativeInit("simgrid-java");
50 isNativeInited = true;
52 /* Don't leak the files on disk */
53 if (tempDir != null) {
54 FileCleaner fclean = new FileCleaner(tempDir.toFile());
59 /** Helper function trying to load one requested library */
60 public static void nativeInit(String name) {
61 Throwable cause = null;
63 /* Prefer the version of the library bundled into the jar file and use it */
64 if (loadLibAsStream(name))
66 } catch (UnsatisfiedLinkError|SecurityException|IOException e) {
70 /* If not found, try to see if we can find a version on disk */
72 System.loadLibrary(name);
74 } catch (UnsatisfiedLinkError systemException) { /* don't care */ }
76 System.err.println("\nCannot load the bindings to the "+name+" library in path "+getPath()+" and no usable SimGrid installation found on disk.");
78 if (cause.getMessage().contains("libcgraph.so"))
79 System.err.println("HINT: Try to install the libcgraph package (sudo apt-get install libcgraph).");
80 else if (cause.getMessage().contains("libboost_context.so"))
81 System.err.println("HINT: Try to install the boost-context package (sudo apt-get install libboost-context-dev).");
83 System.err.println("Try to install the missing dependencies, if any. Read carefully the following error message.");
86 cause.printStackTrace();
88 System.err.println("This jar file does not seem to fit your system, and no usable SimGrid installation found on disk for "+name+".");
93 /** Try to extract the library from the jarfile before loading it */
94 private static boolean loadLibAsStream (String name) throws IOException, UnsatisfiedLinkError {
95 String path = NativeLib.getPath();
97 // We must write the lib onto the disk before loading it -- stupid operating systems
98 if (tempDir == null) {
99 final String tempPrefix = "simgrid-java-";
102 // The cleanup at exit fails on Windows where it is impossible to delete files which are still in
103 // use. Try to remove stale temporary files from previous executions, and limit disk usage.
104 Path tmpdir = (new File(System.getProperty("java.io.tmpdir"))).toPath();
105 try (Stream<Path> paths = Files.find(tmpdir, 1,
106 (Path p, java.nio.file.attribute.BasicFileAttributes a) ->
107 a.isDirectory() && !p.equals(tmpdir) &&
108 p.getFileName().toString().startsWith(tempPrefix))) {
109 paths.map(Path::toFile)
110 .map(FileCleaner::new)
111 .forEach(FileCleaner::run);
116 tempDir = Files.createTempDirectory(tempPrefix);
119 /* For each possible filename of the given library on all possible OSes, try it */
120 for (String filename : new String[]
122 "lib"+name+".so", /* linux */
123 name+".dll", "lib"+name+".dll", /* windows (pure and mingw) */
124 "lib"+name+".dylib" /* macOS */}) {
126 File fileOut = new File(tempDir.toFile(), filename);
127 try ( // Try-with-resources. These stream will be autoclosed when needed.
128 InputStream in = NativeLib.class.getClassLoader().getResourceAsStream(path+filename);
131 /* copy the library in position */
132 Files.copy(in, fileOut.toPath());
134 /* load that library */
135 System.load(fileOut.getAbsolutePath());
137 /* It loaded! we're good */
143 /* No suitable name found */
147 /** Find where to search for the library in the jar -- keep it aligned with where cmake puts it! */
148 private static String getPath() {
149 // Inspiration: https://github.com/xerial/snappy-java/blob/develop/src/main/java/org/xerial/snappy/OSInfo.java
150 String prefix = "NATIVE";
151 String os = System.getProperty("os.name");
152 String arch = System.getProperty("os.arch");
154 if (arch.matches("^i[3-6]86$"))
156 else if ("x86_64".equalsIgnoreCase(arch) || "AMD64".equalsIgnoreCase(arch))
159 if (os.toLowerCase().startsWith("win")) {
161 } else if (os.contains("OS X")) {
164 os = os.replace(' ', '_');
165 arch = arch.replace(' ', '_');
167 return prefix + "/" + os + "/" + arch + "/";
170 /** A hackish mechanism used to remove the file containing our library when the JVM shuts down */
171 private static class FileCleaner implements Runnable {
173 public FileCleaner(File dir) {
178 try (Stream<Path> paths = Files.walk(dir.toPath())) {
179 paths.sorted(java.util.Comparator.reverseOrder())
180 .map(java.nio.file.Path::toFile)
181 //.peek(System.err::println) // Prints what gets removed
182 .forEach(java.io.File::delete);
183 } catch(Exception e) {
184 System.err.println("Error while cleaning temporary file " + dir.getAbsolutePath() +
185 ": " + e.getCause());