-
Notifications
You must be signed in to change notification settings - Fork 89
/
ClosureHelper.java
executable file
·67 lines (54 loc) · 2.56 KB
/
ClosureHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package jnr.ffi.provider.jffi;
import jnr.ffi.Pointer;
import jnr.ffi.Runtime;
import jnr.ffi.mapper.CompositeTypeMapper;
import jnr.ffi.mapper.DefaultSignatureType;
import jnr.ffi.mapper.FromNativeContext;
import jnr.ffi.mapper.FromNativeConverter;
import jnr.ffi.provider.ClosureManager;
import ru.serce.jnrfuse.FuseException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ClosureHelper {
private final AsmClassLoader asmClassLoader;
private final CompositeTypeMapper ctm;
private final SimpleNativeContext ctx;
private final ConcurrentHashMap<Class<?>, FromNativeConverter<?, Pointer>> cache = new ConcurrentHashMap<>();
public static ClosureHelper getInstance() {
return SingletonHolder.INSTANCE;
}
@SuppressWarnings("unchecked")
public <T> FromNativeConverter<T, Pointer> getNativeConveter(Class<T> closureClass) {
FromNativeConverter<T, Pointer> result = (FromNativeConverter<T, Pointer>) cache.get(closureClass);
if (result != null) {
return result;
}
result = (FromNativeConverter<T, Pointer>) ClosureFromNativeConverter.
getInstance(Runtime.getSystemRuntime(), DefaultSignatureType.create(closureClass, (FromNativeContext) ctx), asmClassLoader, ctm);
cache.putIfAbsent(closureClass, result);
return result;
}
public FromNativeContext getFromNativeContext() {
return ctx;
}
private static class SingletonHolder {
private static final ClosureHelper INSTANCE = new ClosureHelper();
}
private ClosureHelper() {
try {
ClosureManager closureManager = jnr.ffi.Runtime.getSystemRuntime().getClosureManager();
Field asmClassLoadersField = NativeClosureManager.class.getDeclaredField("asmClassLoaders");
asmClassLoadersField.setAccessible(true);
Map<ClassLoader, AsmClassLoader> asmClassLoaders = (Map<ClassLoader, AsmClassLoader>) asmClassLoadersField.get(closureManager);
asmClassLoader = asmClassLoaders.get(ClosureHelper.class.getClassLoader());
Field typeMapperField = NativeClosureManager.class.getDeclaredField("typeMapper");
typeMapperField.setAccessible(true);
ctm = (CompositeTypeMapper) typeMapperField.get(closureManager);
ctx = new SimpleNativeContext(Runtime.getSystemRuntime(), Collections.emptyList());
} catch (Exception e) {
throw new FuseException("Unable to create helper", e);
}
}
}