Skip to content

Commit 8a2e995

Browse files
committed
Fix USO_UNSAFE_STATIC_METHOD_SYNCHRONIZATION in LlamaLoader.initialize()
Synchronize on a private static lock object instead of the LlamaLoader class's intrinsic lock, so untrusted code that can reach the public LlamaLoader type cannot acquire the same monitor and interfere with native-library initialization.
1 parent 740b09b commit 8a2e995

1 file changed

Lines changed: 26 additions & 14 deletions

File tree

src/main/java/net/ladenthin/llama/loader/LlamaLoader.java

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,16 @@
4444
@ToString
4545
public class LlamaLoader {
4646

47+
/**
48+
* Private monitor guarding {@link #initialize()}. Synchronizing on this
49+
* dedicated object instead of {@code LlamaLoader.class} keeps the lock
50+
* private to this class, so untrusted code that can reach the public
51+
* {@code LlamaLoader} type cannot acquire the same intrinsic lock and
52+
* interfere with library initialization (SpotBugs
53+
* {@code USO_UNSAFE_STATIC_METHOD_SYNCHRONIZATION}).
54+
*/
55+
private static final Object INITIALIZE_LOCK = new Object();
56+
4757
private static boolean extracted = false;
4858
private static final LlamaSystemProperties systemProperties = new LlamaSystemProperties();
4959
private static final NativeLibraryPermissionSetter permissionSetter = new NativeLibraryPermissionSetter(System.err);
@@ -63,22 +73,24 @@ private LlamaLoader() {}
6373
/**
6474
* Loads the llama and jllama shared libraries
6575
*/
66-
public static synchronized void initialize() {
67-
// only cleanup before the first extract
68-
if (!extracted) {
69-
cleanup();
70-
}
71-
if ("Mac".equals(OSInfo.getOSName())) {
72-
String nativeDirName = getNativeResourcePath();
73-
String tempFolder = getTempDir().getAbsolutePath();
74-
System.out.println(nativeDirName);
75-
Path metalFilePath = extractFile(nativeDirName, "ggml-metal.metal", tempFolder);
76-
if (metalFilePath == null) {
77-
System.err.println("'ggml-metal.metal' not found");
76+
public static void initialize() {
77+
synchronized (INITIALIZE_LOCK) {
78+
// only cleanup before the first extract
79+
if (!extracted) {
80+
cleanup();
81+
}
82+
if ("Mac".equals(OSInfo.getOSName())) {
83+
String nativeDirName = getNativeResourcePath();
84+
String tempFolder = getTempDir().getAbsolutePath();
85+
System.out.println(nativeDirName);
86+
Path metalFilePath = extractFile(nativeDirName, "ggml-metal.metal", tempFolder);
87+
if (metalFilePath == null) {
88+
System.err.println("'ggml-metal.metal' not found");
89+
}
7890
}
91+
loadNativeLibrary("jllama");
92+
extracted = true;
7993
}
80-
loadNativeLibrary("jllama");
81-
extracted = true;
8294
}
8395

8496
/**

0 commit comments

Comments
 (0)