Skip to content

Commit 9ecc427

Browse files
authored
Make sure to always take a copy and avoid anyone writing to it (#66)
1 parent 2b0bcbc commit 9ecc427

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

src/main/java/engineering/swat/watch/impl/mac/NativeLibrary.java

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,12 @@
2828

2929
import static java.nio.file.attribute.PosixFilePermission.*;
3030

31+
import java.io.IOException;
32+
import java.io.OutputStream;
33+
import java.nio.channels.Channels;
3134
import java.nio.file.Files;
35+
import java.nio.file.OpenOption;
36+
import java.nio.file.Path;
3237
import java.nio.file.StandardOpenOption;
3338
import java.nio.file.attribute.FileAttribute;
3439
import java.nio.file.attribute.PosixFilePermission;
@@ -76,20 +81,21 @@ public static void load() {
7681

7782
private static FileAttribute<Set<PosixFilePermission>> PRIVATE_FILE = PosixFilePermissions.asFileAttribute(Set.of(OWNER_READ, OWNER_WRITE , OWNER_EXECUTE));
7883

84+
private static OutputStream openPrivateStream(Path forFile, OpenOption... flags) throws IOException {
85+
return Channels.newOutputStream(
86+
Files.newByteChannel(forFile, Set.of(flags), PRIVATE_FILE)
87+
);
88+
}
89+
7990
private static void loadLibrary(String path) {
8091
try {
81-
var localFile = NativeLibrary.class.getResource(path);
82-
if (localFile != null && localFile.getProtocol().equals("file")) {
83-
System.load(localFile.getPath());
84-
return;
85-
}
8692
// in most cases the file is inside of a jar
8793
// so we have to copy it out and load that file instead
8894
var localCopy = Files.createTempFile("watch", ".dylib", PRIVATE_FILE);
8995
localCopy.toFile().deleteOnExit();
9096
try (var libStream = NativeLibrary.class.getResourceAsStream(path)) {
9197
if (libStream != null) {
92-
try (var writer = Files.newOutputStream(localCopy, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
98+
try (var writer = openPrivateStream(localCopy, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
9399
libStream.transferTo(writer);
94100
}
95101
System.load(localCopy.toString());

0 commit comments

Comments
 (0)