Skip to content

Commit e47803a

Browse files
Aleksei VoitylovAlexander Scherbatiy
Aleksei Voitylov
authored and
Alexander Scherbatiy
committedJul 6, 2021
8266310: deadlock between System.loadLibrary and JNI FindClass loading another class
Reviewed-by: dholmes, plevart, chegar, mchung
1 parent 20eba35 commit e47803a

File tree

10 files changed

+912
-19
lines changed

10 files changed

+912
-19
lines changed
 

‎src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java

+119-19
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import java.util.Map;
4040
import java.util.Set;
4141
import java.util.concurrent.ConcurrentHashMap;
42+
import java.util.concurrent.locks.ReentrantLock;
4243

4344
/**
4445
* Native libraries are loaded via {@link System#loadLibrary(String)},
@@ -185,7 +186,8 @@ private NativeLibrary loadLibrary(Class<?> fromClass, String name, boolean isBui
185186
throw new InternalError(fromClass.getName() + " not allowed to load library");
186187
}
187188

188-
synchronized (loadedLibraryNames) {
189+
acquireNativeLibraryLock(name);
190+
try {
189191
// find if this library has already been loaded and registered in this NativeLibraries
190192
NativeLibrary cached = libraries.get(name);
191193
if (cached != null) {
@@ -202,15 +204,14 @@ private NativeLibrary loadLibrary(Class<?> fromClass, String name, boolean isBui
202204
* When a library is being loaded, JNI_OnLoad function can cause
203205
* another loadLibrary invocation that should succeed.
204206
*
205-
* We use a static stack to hold the list of libraries we are
206-
* loading because this can happen only when called by the
207-
* same thread because this block is synchronous.
207+
* Each thread maintains its own stack to hold the list of
208+
* libraries it is loading.
208209
*
209210
* If there is a pending load operation for the library, we
210-
* immediately return success; otherwise, we raise
211-
* UnsatisfiedLinkError.
211+
* immediately return success; if the pending load is from
212+
* a different class loader, we raise UnsatisfiedLinkError.
212213
*/
213-
for (NativeLibraryImpl lib : nativeLibraryContext) {
214+
for (NativeLibraryImpl lib : NativeLibraryContext.current()) {
214215
if (name.equals(lib.name())) {
215216
if (loader == lib.fromClass.getClassLoader()) {
216217
return lib;
@@ -223,7 +224,7 @@ private NativeLibrary loadLibrary(Class<?> fromClass, String name, boolean isBui
223224

224225
NativeLibraryImpl lib = new NativeLibraryImpl(fromClass, name, isBuiltin, isJNI);
225226
// load the native library
226-
nativeLibraryContext.push(lib);
227+
NativeLibraryContext.push(lib);
227228
try {
228229
if (!lib.open()) {
229230
return null; // fail to open the native library
@@ -242,12 +243,14 @@ private NativeLibrary loadLibrary(Class<?> fromClass, String name, boolean isBui
242243
CleanerFactory.cleaner().register(loader, lib.unloader());
243244
}
244245
} finally {
245-
nativeLibraryContext.pop();
246+
NativeLibraryContext.pop();
246247
}
247248
// register the loaded native library
248249
loadedLibraryNames.add(name);
249250
libraries.put(name, lib);
250251
return lib;
252+
} finally {
253+
releaseNativeLibraryLock(name);
251254
}
252255
}
253256

@@ -295,13 +298,16 @@ public void unload(NativeLibrary lib) {
295298
throw new UnsupportedOperationException("explicit unloading cannot be used with auto unloading");
296299
}
297300
Objects.requireNonNull(lib);
298-
synchronized (loadedLibraryNames) {
301+
acquireNativeLibraryLock(lib.name());
302+
try {
299303
NativeLibraryImpl nl = libraries.remove(lib.name());
300304
if (nl != lib) {
301305
throw new IllegalArgumentException(lib.name() + " not loaded by this NativeLibraries instance");
302306
}
303307
// unload the native library and also remove from the global name registry
304308
nl.unloader().run();
309+
} finally {
310+
releaseNativeLibraryLock(lib.name());
305311
}
306312
}
307313

@@ -415,17 +421,20 @@ static class Unloader implements Runnable {
415421

416422
@Override
417423
public void run() {
418-
synchronized (loadedLibraryNames) {
424+
acquireNativeLibraryLock(name);
425+
try {
419426
/* remove the native library name */
420427
if (!loadedLibraryNames.remove(name)) {
421428
throw new IllegalStateException(name + " has already been unloaded");
422429
}
423-
nativeLibraryContext.push(UNLOADER);
430+
NativeLibraryContext.push(UNLOADER);
424431
try {
425432
unload(name, isBuiltin, isJNI, handle);
426433
} finally {
427-
nativeLibraryContext.pop();
434+
NativeLibraryContext.pop();
428435
}
436+
} finally {
437+
releaseNativeLibraryLock(name);
429438
}
430439
}
431440
}
@@ -443,20 +452,111 @@ static class LibraryPaths {
443452
}
444453

445454
// All native libraries we've loaded.
446-
// This also serves as the lock to obtain nativeLibraries
447-
// and write to nativeLibraryContext.
448-
private static final Set<String> loadedLibraryNames = new HashSet<>();
455+
private static final Set<String> loadedLibraryNames =
456+
ConcurrentHashMap.newKeySet();
457+
458+
// reentrant lock class that allows exact counting (with external synchronization)
459+
@SuppressWarnings("serial")
460+
private static final class CountedLock extends ReentrantLock {
461+
462+
private int counter = 0;
463+
464+
public void increment() {
465+
if (counter == Integer.MAX_VALUE) {
466+
// prevent overflow
467+
throw new Error("Maximum lock count exceeded");
468+
}
469+
++counter;
470+
}
471+
472+
public void decrement() {
473+
--counter;
474+
}
475+
476+
public int getCounter() {
477+
return counter;
478+
}
479+
}
480+
481+
// Maps native library name to the corresponding lock object
482+
private static final Map<String, CountedLock> nativeLibraryLockMap =
483+
new ConcurrentHashMap<>();
484+
485+
private static void acquireNativeLibraryLock(String libraryName) {
486+
nativeLibraryLockMap.compute(libraryName, (name, currentLock) -> {
487+
if (currentLock == null) {
488+
currentLock = new CountedLock();
489+
}
490+
// safe as compute lambda is executed atomically
491+
currentLock.increment();
492+
return currentLock;
493+
}).lock();
494+
}
495+
496+
private static void releaseNativeLibraryLock(String libraryName) {
497+
CountedLock lock = nativeLibraryLockMap.computeIfPresent(libraryName, (name, currentLock) -> {
498+
if (currentLock.getCounter() == 1) {
499+
// unlock and release the object if no other threads are queued
500+
currentLock.unlock();
501+
// remove the element
502+
return null;
503+
} else {
504+
currentLock.decrement();
505+
return currentLock;
506+
}
507+
});
508+
if (lock != null) {
509+
lock.unlock();
510+
}
511+
}
449512

450513
// native libraries being loaded
451-
private static Deque<NativeLibraryImpl> nativeLibraryContext = new ArrayDeque<>(8);
514+
private static final class NativeLibraryContext {
515+
516+
// Maps thread object to the native library context stack, maintained by each thread
517+
private static Map<Thread, Deque<NativeLibraryImpl>> nativeLibraryThreadContext =
518+
new ConcurrentHashMap<>();
519+
520+
// returns a context associated with the current thread
521+
private static Deque<NativeLibraryImpl> current() {
522+
return nativeLibraryThreadContext.computeIfAbsent(
523+
Thread.currentThread(),
524+
t -> new ArrayDeque<>(8));
525+
}
526+
527+
private static NativeLibraryImpl peek() {
528+
return current().peek();
529+
}
530+
531+
private static void push(NativeLibraryImpl lib) {
532+
current().push(lib);
533+
}
534+
535+
private static void pop() {
536+
// this does not require synchronization since each
537+
// thread has its own context
538+
Deque<NativeLibraryImpl> libs = current();
539+
libs.pop();
540+
if (libs.isEmpty()) {
541+
// context can be safely removed once empty
542+
nativeLibraryThreadContext.remove(Thread.currentThread());
543+
}
544+
}
545+
546+
private static boolean isEmpty() {
547+
Deque<NativeLibraryImpl> context =
548+
nativeLibraryThreadContext.get(Thread.currentThread());
549+
return (context == null || context.isEmpty());
550+
}
551+
}
452552

453553
// Invoked in the VM to determine the context class in JNI_OnLoad
454554
// and JNI_OnUnload
455555
private static Class<?> getFromClass() {
456-
if (nativeLibraryContext.isEmpty()) { // only default library
556+
if (NativeLibraryContext.isEmpty()) { // only default library
457557
return Object.class;
458558
}
459-
return nativeLibraryContext.peek().fromClass;
559+
return NativeLibraryContext.peek().fromClass;
460560
}
461561

462562
// JNI FindClass expects the caller class if invoked from JNI_OnLoad
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
/*
26+
* Class1 loads a native library that calls ClassLoader.findClass in JNI_OnLoad.
27+
* Class1 runs concurrently with another thread that opens a signed jar file.
28+
*/
29+
class Class1 {
30+
static {
31+
System.loadLibrary("loadLibraryDeadlock");
32+
System.out.println("Signed jar loaded from native library.");
33+
}
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
/*
26+
* LoadLibraryDeadlock class triggers the deadlock between the two
27+
* lock objects - ZipFile object and ClassLoader.loadedLibraryNames hashmap.
28+
* Thread #2 loads a signed jar which leads to acquiring the lock objects in
29+
* natural order (ZipFile then HashMap) - loading a signed jar may involve
30+
* Providers initialization. Providers may load native libraries.
31+
* Thread #1 acquires the locks in reverse order, first entering loadLibrary
32+
* called from Class1, then acquiring ZipFile during the search for a class
33+
* triggered from JNI.
34+
*/
35+
import java.lang.*;
36+
37+
public class LoadLibraryDeadlock {
38+
39+
public static void main(String[] args) {
40+
Thread t1 = new Thread() {
41+
public void run() {
42+
try {
43+
// an instance of unsigned class that loads a native library
44+
Class<?> c1 = Class.forName("Class1");
45+
Object o = c1.newInstance();
46+
} catch (ClassNotFoundException |
47+
InstantiationException |
48+
IllegalAccessException e) {
49+
System.out.println("Class Class1 not found.");
50+
throw new RuntimeException(e);
51+
}
52+
}
53+
};
54+
Thread t2 = new Thread() {
55+
public void run() {
56+
try {
57+
// load a class from a signed jar, which locks the JarFile
58+
Class<?> c2 = Class.forName("p.Class2");
59+
System.out.println("Signed jar loaded.");
60+
} catch (ClassNotFoundException e) {
61+
System.out.println("Class Class2 not found.");
62+
throw new RuntimeException(e);
63+
}
64+
}
65+
};
66+
t2.start();
67+
t1.start();
68+
try {
69+
t1.join();
70+
t2.join();
71+
} catch (InterruptedException ignore) {
72+
}
73+
}
74+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
/*
26+
* @test
27+
* @bug 8266310
28+
* @summary Checks if there's no deadlock between the two lock objects -
29+
* class loading lock and ClassLoader.loadedLibraryNames hashmap.
30+
* @library /test/lib
31+
* @build LoadLibraryDeadlock Class1 p.Class2
32+
* @run main/othervm/native -Xcheck:jni TestLoadLibraryDeadlock
33+
*/
34+
35+
import jdk.test.lib.Asserts;
36+
import jdk.test.lib.JDKToolFinder;
37+
import jdk.test.lib.process.*;
38+
import jdk.test.lib.util.FileUtils;
39+
40+
import java.lang.ProcessBuilder;
41+
import java.lang.Process;
42+
import java.nio.file.Paths;
43+
import java.io.*;
44+
import java.util.*;
45+
import java.util.concurrent.*;
46+
import java.util.spi.ToolProvider;
47+
48+
public class TestLoadLibraryDeadlock {
49+
50+
private static final ToolProvider JAR = ToolProvider.findFirst("jar")
51+
.orElseThrow(() -> new RuntimeException("ToolProvider for jar not found"));
52+
53+
private static final String KEYSTORE = "keystore.jks";
54+
private static final String STOREPASS = "changeit";
55+
private static final String KEYPASS = "changeit";
56+
private static final String ALIAS = "test";
57+
private static final String DNAME = "CN=test";
58+
private static final String VALIDITY = "366";
59+
60+
private static String testClassPath = System.getProperty("test.classes");
61+
private static String testLibraryPath = System.getProperty("test.nativepath");
62+
private static String classPathSeparator = System.getProperty("path.separator");
63+
64+
private static OutputAnalyzer runCommand(File workingDirectory, String... commands) throws Throwable {
65+
ProcessBuilder pb = new ProcessBuilder(commands);
66+
pb.directory(workingDirectory);
67+
System.out.println("COMMAND: " + String.join(" ", commands));
68+
return ProcessTools.executeProcess(pb);
69+
}
70+
71+
private static OutputAnalyzer runCommandInTestClassPath(String... commands) throws Throwable {
72+
return runCommand(new File(testClassPath), commands);
73+
}
74+
75+
private static OutputAnalyzer genKey() throws Throwable {
76+
FileUtils.deleteFileIfExistsWithRetry(
77+
Paths.get(testClassPath, KEYSTORE));
78+
String keytool = JDKToolFinder.getJDKTool("keytool");
79+
return runCommandInTestClassPath(keytool,
80+
"-storepass", STOREPASS,
81+
"-keypass", KEYPASS,
82+
"-keystore", KEYSTORE,
83+
"-keyalg", "rsa", "-keysize", "2048",
84+
"-genkeypair",
85+
"-alias", ALIAS,
86+
"-dname", DNAME,
87+
"-validity", VALIDITY
88+
);
89+
}
90+
91+
private static void createJar(String outputJar, String... classes) throws Throwable {
92+
List<String> args = new ArrayList<>();
93+
Collections.addAll(args, "cvf", Paths.get(testClassPath, outputJar).toString());
94+
for (String c : classes) {
95+
Collections.addAll(args, "-C", testClassPath, c);
96+
}
97+
if (JAR.run(System.out, System.err, args.toArray(new String[0])) != 0) {
98+
throw new RuntimeException("jar operation failed");
99+
}
100+
}
101+
102+
private static OutputAnalyzer signJar(String jarToSign) throws Throwable {
103+
String jarsigner = JDKToolFinder.getJDKTool("jarsigner");
104+
return runCommandInTestClassPath(jarsigner,
105+
"-keystore", KEYSTORE,
106+
"-storepass", STOREPASS,
107+
jarToSign, ALIAS
108+
);
109+
}
110+
111+
private static Process runJavaCommand(String... command) throws Throwable {
112+
String java = JDKToolFinder.getJDKTool("java");
113+
List<String> commands = new ArrayList<>();
114+
Collections.addAll(commands, java);
115+
Collections.addAll(commands, command);
116+
System.out.println("COMMAND: " + String.join(" ", commands));
117+
return new ProcessBuilder(commands.toArray(new String[0]))
118+
.redirectErrorStream(true)
119+
.directory(new File(testClassPath))
120+
.start();
121+
}
122+
123+
private static OutputAnalyzer jcmd(long pid, String command) throws Throwable {
124+
String jcmd = JDKToolFinder.getJDKTool("jcmd");
125+
return runCommandInTestClassPath(jcmd,
126+
String.valueOf(pid),
127+
command
128+
);
129+
}
130+
131+
private static String readAvailable(final InputStream is) throws Throwable {
132+
final List<String> list = Collections.synchronizedList(new ArrayList<String>());
133+
ExecutorService executor = Executors.newFixedThreadPool(2);
134+
Future<String> future = executor.submit(new Callable<String>() {
135+
public String call() {
136+
String result = new String();
137+
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
138+
try {
139+
while(true) {
140+
String s = reader.readLine();
141+
if (s.length() > 0) {
142+
list.add(s);
143+
result += s + "\n";
144+
}
145+
}
146+
} catch (IOException ignore) {}
147+
return result;
148+
}
149+
});
150+
try {
151+
return future.get(1000, TimeUnit.MILLISECONDS);
152+
} catch (Exception ignoreAll) {
153+
future.cancel(true);
154+
return String.join("\n", list);
155+
}
156+
}
157+
158+
private final static long countLines(OutputAnalyzer output, String string) {
159+
return output.asLines()
160+
.stream()
161+
.filter(s -> s.contains(string))
162+
.count();
163+
}
164+
165+
private final static void dump(OutputAnalyzer output) {
166+
output.asLines()
167+
.stream()
168+
.forEach(s -> System.out.println(s));
169+
}
170+
171+
public static void main(String[] args) throws Throwable {
172+
genKey()
173+
.shouldHaveExitValue(0);
174+
175+
FileUtils.deleteFileIfExistsWithRetry(
176+
Paths.get(testClassPath, "a.jar"));
177+
FileUtils.deleteFileIfExistsWithRetry(
178+
Paths.get(testClassPath, "b.jar"));
179+
FileUtils.deleteFileIfExistsWithRetry(
180+
Paths.get(testClassPath, "c.jar"));
181+
182+
createJar("a.jar",
183+
"LoadLibraryDeadlock.class",
184+
"LoadLibraryDeadlock$1.class",
185+
"LoadLibraryDeadlock$2.class");
186+
187+
createJar("b.jar",
188+
"Class1.class");
189+
190+
createJar("c.jar",
191+
"p/Class2.class");
192+
193+
signJar("c.jar")
194+
.shouldHaveExitValue(0);
195+
196+
// load trigger class
197+
Process process = runJavaCommand("-cp",
198+
"a.jar" + classPathSeparator +
199+
"b.jar" + classPathSeparator +
200+
"c.jar",
201+
"-Djava.library.path=" + testLibraryPath,
202+
"LoadLibraryDeadlock");
203+
204+
// wait for a while to grab some output
205+
process.waitFor(5, TimeUnit.SECONDS);
206+
207+
// dump available output
208+
String output = readAvailable(process.getInputStream());
209+
OutputAnalyzer outputAnalyzer = new OutputAnalyzer(output);
210+
dump(outputAnalyzer);
211+
212+
// if the process is still running, get the thread dump
213+
OutputAnalyzer outputAnalyzerJcmd = jcmd(process.pid(), "Thread.print");
214+
dump(outputAnalyzerJcmd);
215+
216+
Asserts.assertTrue(
217+
countLines(outputAnalyzer, "Java-level deadlock") == 0,
218+
"Found a deadlock.");
219+
220+
// if no deadlock, make sure all components have been loaded
221+
Asserts.assertTrue(
222+
countLines(outputAnalyzer, "Class Class1 not found.") == 0,
223+
"Unable to load class. Class1 not found.");
224+
225+
Asserts.assertTrue(
226+
countLines(outputAnalyzer, "Class Class2 not found.") == 0,
227+
"Unable to load class. Class2 not found.");
228+
229+
Asserts.assertTrue(
230+
countLines(outputAnalyzer, "Native library loaded.") > 0,
231+
"Unable to load native library.");
232+
233+
Asserts.assertTrue(
234+
countLines(outputAnalyzer, "Signed jar loaded.") > 0,
235+
"Unable to load signed jar.");
236+
237+
Asserts.assertTrue(
238+
countLines(outputAnalyzer, "Signed jar loaded from native library.") > 0,
239+
"Unable to load signed jar from native library.");
240+
241+
if (!process.waitFor(5, TimeUnit.SECONDS)) {
242+
// if the process is still frozen, fail the test even though
243+
// the "deadlock" text hasn't been found
244+
process.destroyForcibly();
245+
Asserts.assertTrue(process.waitFor() == 0,
246+
"Process frozen.");
247+
}
248+
}
249+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
#include <stdio.h>
26+
#include "jni.h"
27+
28+
/*
29+
* Native library that loads an arbitrary class from a (signed) jar.
30+
* This triggers the search in jars, and the lock in ZipFile is acquired
31+
* as a result.
32+
*/
33+
JNIEXPORT jint JNICALL
34+
JNI_OnLoad(JavaVM *vm, void *reserved)
35+
{
36+
JNIEnv *env;
37+
jclass cl;
38+
39+
printf("Native library loaded.\n");
40+
fflush(stdout);
41+
42+
if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_2) != JNI_OK) {
43+
return JNI_EVERSION; /* JNI version not supported */
44+
}
45+
46+
// find any class which triggers the search in jars
47+
cl = (*env)->FindClass(env, "p/Class2");
48+
49+
return JNI_VERSION_1_2;
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
/*
26+
* Class2 is loaded from Thread #2 that checks jar signature and from
27+
* Thread #1 that loads a native library.
28+
*/
29+
package p;
30+
31+
class Class2 {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
/*
26+
* LoadLibraryUnload class calls ClassLoader.loadedLibrary from multiple threads
27+
*/
28+
/*
29+
* @test
30+
* @bug 8266310
31+
* @summary Loads a native library from multiple class loaders and multiple
32+
* threads. This creates a race for loading the library. The winner
33+
* loads the library in two threads. All threads except two would fail
34+
* with UnsatisfiedLinkError when the class being loaded is already
35+
* loaded in a different class loader that won the race. The test
36+
* checks that the loaded class is GC'ed, that means the class loader
37+
* is GC'ed and the native library is unloaded.
38+
* @library /test/lib
39+
* @build LoadLibraryUnload p.Class1
40+
* @run main/othervm/native -Xcheck:jni LoadLibraryUnload
41+
*/
42+
import jdk.test.lib.Asserts;
43+
import jdk.test.lib.util.ForceGC;
44+
import java.lang.*;
45+
import java.lang.reflect.*;
46+
import java.lang.ref.WeakReference;
47+
import java.net.URL;
48+
import java.net.URLClassLoader;
49+
import java.nio.file.Path;
50+
import java.util.ArrayList;
51+
import java.util.List;
52+
import java.util.Set;
53+
import java.util.concurrent.ConcurrentHashMap;
54+
55+
import p.Class1;
56+
57+
public class LoadLibraryUnload {
58+
59+
private static class TestLoader extends URLClassLoader {
60+
public TestLoader() throws Exception {
61+
super(new URL[] { Path.of(System.getProperty("test.classes")).toUri().toURL() });
62+
}
63+
64+
@Override
65+
public Class<?> loadClass(String name) throws ClassNotFoundException {
66+
synchronized (getClassLoadingLock(name)) {
67+
Class<?> clazz = findLoadedClass(name);
68+
if (clazz == null) {
69+
try {
70+
clazz = findClass(name);
71+
} catch (ClassNotFoundException ignore) {
72+
}
73+
if (clazz == null) {
74+
clazz = super.loadClass(name);
75+
}
76+
}
77+
return clazz;
78+
}
79+
}
80+
}
81+
82+
private static class LoadLibraryFromClass implements Runnable {
83+
Object object;
84+
Method method;
85+
86+
public LoadLibraryFromClass(Class<?> fromClass) {
87+
try {
88+
this.object = fromClass.newInstance();
89+
this.method = fromClass.getDeclaredMethod("loadLibrary");
90+
} catch (ReflectiveOperationException roe) {
91+
throw new RuntimeException(roe);
92+
}
93+
}
94+
95+
@Override
96+
public void run() {
97+
try {
98+
method.invoke(object);
99+
} catch (ReflectiveOperationException roe) {
100+
throw new RuntimeException(roe);
101+
}
102+
}
103+
}
104+
105+
public static void main(String[] args) throws Exception {
106+
107+
Class<?> clazz = null;
108+
List<Thread> threads = new ArrayList<>();
109+
110+
for (int i = 0 ; i < 5 ; i++) {
111+
// 5 loaders and 10 threads in total.
112+
// winner loads the library in 2 threads
113+
clazz = new TestLoader().loadClass("p.Class1");
114+
threads.add(new Thread(new LoadLibraryFromClass(clazz)));
115+
threads.add(new Thread(new LoadLibraryFromClass(clazz)));
116+
}
117+
118+
final Set<Throwable> exceptions = ConcurrentHashMap.newKeySet();
119+
threads.forEach( t -> {
120+
t.setUncaughtExceptionHandler((th, ex) -> {
121+
// collect the root cause of each failure
122+
Throwable rootCause = ex;
123+
while((ex = ex.getCause()) != null) {
124+
rootCause = ex;
125+
}
126+
exceptions.add(rootCause);
127+
});
128+
t.start();
129+
});
130+
131+
// wait for all threads to finish
132+
for (Thread t : threads) {
133+
t.join();
134+
}
135+
136+
// expect all errors to be UnsatisfiedLinkError
137+
boolean allAreUnsatisfiedLinkError = exceptions
138+
.stream()
139+
.map(e -> e instanceof UnsatisfiedLinkError)
140+
.reduce(true, (i, a) -> i && a);
141+
142+
// expect exactly 8 errors
143+
Asserts.assertTrue(exceptions.size() == 8,
144+
"Expected to see 8 failing threads");
145+
146+
Asserts.assertTrue(allAreUnsatisfiedLinkError,
147+
"All errors have to be UnsatisfiedLinkError");
148+
149+
WeakReference<Class<?>> wClass = new WeakReference<>(clazz);
150+
151+
// release strong refs
152+
clazz = null;
153+
threads = null;
154+
exceptions.clear();
155+
ForceGC gc = new ForceGC();
156+
if (!gc.await(() -> wClass.refersTo(null))) {
157+
throw new RuntimeException("Class1 hasn't been GC'ed");
158+
}
159+
}
160+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
/*
26+
* LoadLibraryUnloadTest ensures all objects (NativeLibrary) are deallocated
27+
* when loaded in concurrent mode.
28+
*/
29+
/*
30+
* @test
31+
* @bug 8266310
32+
* @summary Checks that JNI_OnLoad is invoked only once when multiple threads
33+
* call System.loadLibrary concurrently, and JNI_OnUnload is invoked
34+
* when the native library is loaded from a custom class loader.
35+
* @library /test/lib
36+
* @build LoadLibraryUnload p.Class1
37+
* @run main/othervm/native -Xcheck:jni LoadLibraryUnloadTest
38+
*/
39+
40+
import jdk.test.lib.Asserts;
41+
import jdk.test.lib.JDKToolFinder;
42+
import jdk.test.lib.process.*;
43+
44+
import java.lang.ProcessBuilder;
45+
import java.lang.Process;
46+
import java.io.File;
47+
import java.util.*;
48+
49+
public class LoadLibraryUnloadTest {
50+
51+
private static String testClassPath = System.getProperty("test.classes");
52+
private static String testLibraryPath = System.getProperty("test.nativepath");
53+
private static String classPathSeparator = System.getProperty("path.separator");
54+
55+
private static Process runJavaCommand(String... command) throws Throwable {
56+
String java = JDKToolFinder.getJDKTool("java");
57+
List<String> commands = new ArrayList<>();
58+
Collections.addAll(commands, java);
59+
Collections.addAll(commands, command);
60+
System.out.println("COMMAND: " + String.join(" ", commands));
61+
return new ProcessBuilder(commands.toArray(new String[0]))
62+
.redirectErrorStream(true)
63+
.directory(new File(testClassPath))
64+
.start();
65+
}
66+
67+
private final static long countLines(OutputAnalyzer output, String string) {
68+
return output.asLines()
69+
.stream()
70+
.filter(s -> s.contains(string))
71+
.count();
72+
}
73+
74+
private final static void dump(OutputAnalyzer output) {
75+
output.asLines()
76+
.stream()
77+
.forEach(s -> System.out.println(s));
78+
}
79+
80+
public static void main(String[] args) throws Throwable {
81+
82+
Process process = runJavaCommand(
83+
"-Dtest.classes=" + testClassPath,
84+
"-Djava.library.path=" + testLibraryPath,
85+
"LoadLibraryUnload");
86+
87+
OutputAnalyzer outputAnalyzer = new OutputAnalyzer(process);
88+
dump(outputAnalyzer);
89+
90+
Asserts.assertTrue(
91+
countLines(outputAnalyzer, "Native library loaded from Class1.") == 2,
92+
"Native library expected to be loaded in 2 threads.");
93+
94+
long refCount = countLines(outputAnalyzer, "Native library loaded.");
95+
96+
Asserts.assertTrue(refCount > 0, "Failed to load native library.");
97+
98+
System.out.println("Native library loaded in " + refCount + " threads");
99+
100+
Asserts.assertTrue(refCount == 1, "Native library is loaded more than once.");
101+
102+
Asserts.assertTrue(
103+
countLines(outputAnalyzer, "Native library unloaded.") == refCount,
104+
"Failed to unload native library");
105+
}
106+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
#include <stdio.h>
26+
#include "jni.h"
27+
28+
JNIEXPORT jint JNICALL
29+
JNI_OnLoad(JavaVM *vm, void *reserved)
30+
{
31+
JNIEnv *env;
32+
33+
printf("Native library loaded.\n");
34+
fflush(stdout);
35+
36+
if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_2) != JNI_OK) {
37+
return JNI_EVERSION; /* JNI version not supported */
38+
}
39+
40+
return JNI_VERSION_1_2;
41+
}
42+
43+
JNIEXPORT void JNICALL
44+
JNI_OnUnload(JavaVM *vm, void *reserved) {
45+
46+
printf("Native library unloaded.\n");
47+
fflush(stdout);
48+
}
49+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* Copyright (c) 2021, BELLSOFT. All rights reserved.
4+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5+
*
6+
* This code is free software; you can redistribute it and/or modify it
7+
* under the terms of the GNU General Public License version 2 only, as
8+
* published by the Free Software Foundation.
9+
*
10+
* This code is distributed in the hope that it will be useful, but WITHOUT
11+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13+
* version 2 for more details (a copy is included in the LICENSE file that
14+
* accompanied this code).
15+
*
16+
* You should have received a copy of the GNU General Public License version
17+
* 2 along with this work; if not, write to the Free Software Foundation,
18+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19+
*
20+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21+
* or visit www.oracle.com if you need additional information or have any
22+
* questions.
23+
*/
24+
25+
/*
26+
* Class1 loads a native library.
27+
*/
28+
package p;
29+
30+
public class Class1 {
31+
32+
public Class1() {
33+
}
34+
35+
// method called from java threads
36+
public void loadLibrary() throws Exception {
37+
System.loadLibrary("loadLibraryUnload");
38+
System.out.println("Native library loaded from Class1.");
39+
}
40+
}

0 commit comments

Comments
 (0)
Please sign in to comment.