Skip to content

Commit 9872659

Browse files
committed
Release discarded library class loaders retained by cached options
Generated-by: OpenAI Codex
1 parent a800ca8 commit 9872659

5 files changed

Lines changed: 186 additions & 1 deletion

File tree

‎CHANGES.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ Features
1010

1111
Bug Fixes
1212
---------
13+
14+
* Allow discarded library class loaders to be collected on JVMs by associating cached options with their classes. Android retains the existing cache for compatibility with runtimes without `ClassValue`. See [#1742](https://github.com/java-native-access/jna/issues/1742).
1315
* [#1740](https://github.com/java-native-access/jna/issues/1740): Fix `c.s.j.p.unix.solaris.LibKstat.KstatCtl` mapping `kc_chain` as an inline `Kstat` instead of a pointer, which made every call taking a `KstatCtl` write past the end of the structure `kstat_open()` allocated, and map the `Kstat` function pointers `ks_update` and `ks_snapshot` as `Pointer` instead of `int` - [@dbwiddis](https://github.com/dbwiddis).
1416

1517
Breaking Changes

‎build.xml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@
272272

273273
<target name=":jar">
274274
<uptodate property="-jar" targetfile="${build}/${jar}">
275+
<srcfiles dir="${src}" includes="META-INF/proguard/*.pro"/>
275276
<srcfiles dir="${classes}">
276277
<patternset id="jar-compiled">
277278
<include name="com/sun/jna/*"/>
@@ -450,6 +451,7 @@ osname=macosx;processor=aarch64
450451
<requires module="java.desktop" />
451452
</ModuleGenerator>
452453
<jar jarfile="${build}/${jar}" duplicate="preserve" createUnicodeExtraFields="never" encoding="UTF-8" manifest="${build}/manifest/automatic.mf">
454+
<zipfileset dir="${src}" includes="META-INF/proguard/*.pro"/>
453455
<fileset dir="${classes}" excludes="${jar.omitted}">
454456
<patternset refid="jar-compiled"/>
455457
</fileset>
@@ -587,6 +589,7 @@ osname=macosx;processor=aarch64
587589
<!-- Dummy entries in R.txt and the string resources are needed or a grails
588590
build using this library will fail (tested with Android Studio 2.2.3 -->
589591
<mkdir dir="${build.aar}/res/values" />
592+
<copy file="${src}/META-INF/proguard/jna.pro" tofile="${build.aar}/proguard.txt"/>
590593
<echo file="${build.aar}/res/values/values.xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
591594
<resources>
592595
<string name="jna_library_appname">JNA bindings</string>

‎src/META-INF/proguard/jna.pro‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Copyright (c) 2026 curforever. All Rights Reserved.
2+
# Dual-licensed under LGPL 2.1 or later and Apache License 2.0.
3+
# See LGPL2.1 and AL2.0 distributed with JNA.
4+
# Android selects the legacy options cache and never loads the JVM-only backend.
5+
# Older Android boot class paths do not declare this optional Java API.
6+
-dontwarn java.lang.ClassValue

‎src/com/sun/jna/Native.java‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
import java.util.Map;
6363
import java.util.StringTokenizer;
6464
import java.util.WeakHashMap;
65+
import java.util.concurrent.atomic.AtomicReference;
6566
import java.util.logging.Level;
6667
import java.util.logging.Logger;
6768
import java.util.stream.Stream;
@@ -147,7 +148,56 @@ public final class Native implements Version {
147148

148149
// Used by tests, do not remove
149150
static String jnidispatchPath = null;
150-
private static final Map<Class<?>, Map<String, Object>> typeOptions = Collections.synchronizedMap(new WeakHashMap<Class<?>, Map<String, Object>>());
151+
private static final TypeOptions typeOptions = TypeOptionsCache.create(Platform.isAndroid());
152+
153+
private interface TypeOptions {
154+
Map<String, Object> get(Class<?> type);
155+
void put(Class<?> type, Map<String, Object> options);
156+
}
157+
158+
private static class TypeOptionsCache {
159+
static TypeOptions create(boolean android) {
160+
// Older Android runtimes do not provide java.lang.ClassValue.
161+
return android ? new WeakMapTypeOptions() : new ClassValueTypeOptions();
162+
}
163+
}
164+
165+
private static class WeakMapTypeOptions implements TypeOptions {
166+
private final Map<Class<?>, Map<String, Object>> options =
167+
Collections.synchronizedMap(new WeakHashMap<Class<?>, Map<String, Object>>());
168+
169+
@Override
170+
public Map<String, Object> get(Class<?> type) {
171+
return options.get(type);
172+
}
173+
174+
@Override
175+
public void put(Class<?> type, Map<String, Object> value) {
176+
options.put(type, value);
177+
}
178+
}
179+
180+
private static class ClassValueTypeOptions implements TypeOptions {
181+
// Values may refer to the class or its loader (e.g. a custom TypeMapper).
182+
// ClassValue keeps that cycle local to the class, rather than in a static map.
183+
private final ClassValue<AtomicReference<Map<String, Object>>> options =
184+
new ClassValue<AtomicReference<Map<String, Object>>>() {
185+
@Override
186+
protected AtomicReference<Map<String, Object>> computeValue(Class<?> type) {
187+
return new AtomicReference<>();
188+
}
189+
};
190+
191+
@Override
192+
public Map<String, Object> get(Class<?> type) {
193+
return options.get(type).get();
194+
}
195+
196+
@Override
197+
public void put(Class<?> type, Map<String, Object> value) {
198+
options.get(type).set(value);
199+
}
200+
}
151201
private static final Map<Class<?>, Reference<?>> libraries = Collections.synchronizedMap(new WeakHashMap<Class<?>, Reference<?>>());
152202
private static final String _OPTION_ENCLOSING_LIBRARY = "enclosing-library";
153203
private static final UncaughtExceptionHandler DEFAULT_HANDLER =

‎test/com/sun/jna/NativeTest.java‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,11 @@
2323
*/
2424
package com.sun.jna;
2525

26+
import java.io.ByteArrayOutputStream;
2627
import java.io.File;
28+
import java.io.IOException;
29+
import java.io.InputStream;
30+
import java.lang.ref.WeakReference;
2731
import java.lang.reflect.Method;
2832
import java.nio.charset.Charset;
2933
import java.util.Arrays;
@@ -38,6 +42,126 @@
3842
//@SuppressWarnings("unused")
3943
public class NativeTest extends TestCase {
4044

45+
46+
public interface CollectibleLibrary extends Library {
47+
int abs(int value);
48+
49+
class Mapper extends DefaultTypeMapper {
50+
}
51+
52+
@Structure.FieldOrder({"value"})
53+
class Value extends Structure {
54+
public int value;
55+
}
56+
}
57+
58+
private static class CollectibleClassLoader extends ClassLoader {
59+
CollectibleClassLoader() {
60+
super(NativeTest.class.getClassLoader());
61+
}
62+
63+
@Override
64+
protected synchronized Class<?> loadClass(String name, boolean resolve)
65+
throws ClassNotFoundException {
66+
if (!name.startsWith(CollectibleLibrary.class.getName())) {
67+
return super.loadClass(name, resolve);
68+
}
69+
Class<?> type = findLoadedClass(name);
70+
if (type == null) {
71+
String resource = "/" + name.replace('.', '/') + ".class";
72+
try (InputStream stream = NativeTest.class.getResourceAsStream(resource)) {
73+
if (stream == null) {
74+
throw new ClassNotFoundException(name);
75+
}
76+
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
77+
byte[] buffer = new byte[1024];
78+
int length;
79+
while ((length = stream.read(buffer)) != -1) {
80+
bytes.write(buffer, 0, length);
81+
}
82+
byte[] content = bytes.toByteArray();
83+
type = defineClass(name, content, 0, content.length);
84+
} catch (IOException e) {
85+
throw new ClassNotFoundException(name, e);
86+
}
87+
}
88+
if (resolve) {
89+
resolveClass(type);
90+
}
91+
return type;
92+
}
93+
}
94+
95+
@SuppressWarnings("unchecked")
96+
private WeakReference<ClassLoader> loadCollectibleLibrary(boolean withMapper,
97+
boolean withLoader) throws Exception {
98+
ClassLoader loader = new CollectibleClassLoader();
99+
Class<? extends Library> type = (Class<? extends Library>)
100+
loader.loadClass(CollectibleLibrary.class.getName());
101+
Map<String, Object> options = new HashMap<>();
102+
if (withMapper) {
103+
Object mapper = loader.loadClass(CollectibleLibrary.Mapper.class.getName())
104+
.getDeclaredConstructor().newInstance();
105+
assertSame(loader, mapper.getClass().getClassLoader());
106+
options.put(Library.OPTION_TYPE_MAPPER, mapper);
107+
}
108+
if (withLoader) {
109+
options.put(Library.OPTION_CLASSLOADER, loader);
110+
}
111+
Library library = Native.load(Platform.C_LIBRARY_NAME, type, options);
112+
assertEquals(7, type.getMethod("abs", int.class).invoke(library, -7));
113+
Class<?> nested = loader.loadClass(CollectibleLibrary.Value.class.getName());
114+
assertSame(loader, type.getClassLoader());
115+
assertSame(loader, nested.getClassLoader());
116+
assertSame(Native.getLibraryOptions(type), Native.getLibraryOptions(nested));
117+
assertSame(type, Native.findEnclosingLibraryClass(nested));
118+
assertSame(options.get(Library.OPTION_TYPE_MAPPER), Native.getTypeMapper(nested));
119+
return new WeakReference<>(loader);
120+
}
121+
122+
private void assertClassLoaderCollected(WeakReference<ClassLoader> loader) throws Exception {
123+
for (int i = 0; i < 100 && loader.get() != null; i++) {
124+
System.gc();
125+
Thread.sleep(50);
126+
}
127+
assertNull("Discarded library class loader is retained by cached options", loader.get());
128+
}
129+
130+
public void testDiscardedLibraryClassLoader() throws Exception {
131+
assertClassLoaderCollected(loadCollectibleLibrary(false, false));
132+
}
133+
134+
public void testDiscardedLibraryClassLoaderWithTypeMapper() throws Exception {
135+
assertClassLoaderCollected(loadCollectibleLibrary(true, false));
136+
}
137+
138+
public void testDiscardedLibraryClassLoaderWithLoaderOption() throws Exception {
139+
assertClassLoaderCollected(loadCollectibleLibrary(false, true));
140+
}
141+
142+
@SuppressWarnings("unchecked")
143+
public void testLibraryOptionsRetainedWhileClassIsLive() throws Exception {
144+
ClassLoader loader = new CollectibleClassLoader();
145+
Class<? extends Library> type = (Class<? extends Library>)
146+
loader.loadClass(CollectibleLibrary.class.getName());
147+
Object mapper = loader.loadClass(CollectibleLibrary.Mapper.class.getName())
148+
.getDeclaredConstructor().newInstance();
149+
Map<String, Object> options = new HashMap<>();
150+
options.put(Library.OPTION_TYPE_MAPPER, mapper);
151+
Library library = Native.load(Platform.C_LIBRARY_NAME, type, options);
152+
Class<?> nested = loader.loadClass(CollectibleLibrary.Value.class.getName());
153+
Map<String, Object> cached = Native.getLibraryOptions(type);
154+
assertSame(cached, Native.getLibraryOptions(nested));
155+
for (int i = 0; i < 3; i++) {
156+
System.gc();
157+
assertSame(cached, Native.getLibraryOptions(type));
158+
assertSame(cached, Native.getLibraryOptions(nested));
159+
assertSame(mapper, Native.getTypeMapper(nested));
160+
assertSame(type, Native.findEnclosingLibraryClass(nested));
161+
assertEquals(7, type.getMethod("abs", int.class).invoke(library, -7));
162+
}
163+
}
164+
41165
private static final String UNICODE = "[\u0444]";
42166

43167
public void testLoadLibraryMethods() throws Exception {

0 commit comments

Comments
 (0)