-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathJNICore.swift
309 lines (267 loc) · 10.9 KB
/
JNICore.swift
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//
// JavaJNI.swift
// SwiftJava
//
// Created by John Holdsworth on 13/07/2016.
// Copyright (c) 2016 John Holdsworth. All rights reserved.
//
// Basic JNI functionality notably initialising a JVM on Unix
// as well as maintaining cache of currently attached JNI.env
//
import Foundation
import Dispatch
@_exported import CJavaVM
@_silgen_name("JNI_OnLoad")
public func JNI_OnLoad( jvm: UnsafeMutablePointer<JavaVM?>, ptr: UnsafeRawPointer ) -> jint {
JNI.jvm = jvm
let env: UnsafeMutablePointer<JNIEnv?>? = JNI.GetEnv()
JNI.api = env!.pointee!.pointee
if pthread_setspecific( JNICore.envVarKey, env ) != 0 {
JNI.report( "Could not set pthread specific GetEnv()" )
}
// Save ContextClassLoader for FindClass usage
// When a thread is attached to the VM, the context class loader is the bootstrap loader.
// https://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/invocation.html
// https://developer.android.com/training/articles/perf-jni.html#faq_FindClass
JNI.classLoader = JavaThread.currentThread().getContextClassLoader().withJavaObject { JNI.api.NewGlobalRef( env, $0 ) }
return jint(JNI_VERSION_1_6)
}
public func JNI_DetachCurrentThread() {
_ = JNI.jvm?.pointee?.pointee.DetachCurrentThread( JNI.jvm )
}
public let JNI = JNICore()
open class JNICore {
open var jvm: UnsafeMutablePointer<JavaVM?>?
open var api: JNINativeInterface_!
open var classLoader: jobject?
static var envVarKey: pthread_key_t = {
var envVarKey: pthread_key_t = 0
if pthread_key_create( &envVarKey, { _ in
_ = JNI.jvm?.pointee?.pointee.DetachCurrentThread( JNI.jvm )
}) != 0 {
JNI.report( "Could not create pthread envVarKey" )
}
return envVarKey
}()
open var env: UnsafeMutablePointer<JNIEnv?>? {
if let existing = pthread_getspecific( JNICore.envVarKey ) {
return existing.assumingMemoryBound(to: JNIEnv?.self)
}
let env = AttachCurrentThread()
if pthread_setspecific( JNICore.envVarKey, env ) != 0 {
JNI.report( "Could not set pthread specific env" )
}
return env
}
open func AttachCurrentThread() -> UnsafeMutablePointer<JNIEnv?>? {
var tenv: UnsafeMutablePointer<JNIEnv?>?
if withPointerToRawPointer(to: &tenv, {
self.jvm?.pointee?.pointee.AttachCurrentThread( self.jvm, $0, nil )
} ) != jint(JNI_OK) {
report( "Could not attach to background jvm" )
}
return tenv
}
open func report( _ msg: String, _ file: StaticString = #file, _ line: Int = #line ) {
NSLog( "\(msg) - at \(file):\(line)" )
if api?.ExceptionCheck( env ) != 0 {
api.ExceptionDescribe( env )
}
}
open func initJVM( options: [String]? = nil, _ file: StaticString = #file, _ line: Int = #line ) -> Bool {
#if os(Android)
return true
#else
if jvm != nil {
report( "JVM can only be initialised once", file, line )
return true
}
var options: [String]? = options
if options == nil {
var classpath: String = String( cString: getenv("HOME") )+"/.swiftjava.jar"
if let CLASSPATH: UnsafeMutablePointer<Int8> = getenv( "CLASSPATH" ) {
classpath += ":"+String( cString: CLASSPATH )
}
options = ["-Djava.class.path="+classpath,
// add to bootclasspath as threads not started using Thread class
// will not have the correct classloader and be missing classpath
"-Xbootclasspath/a:"+classpath]
}
var vmOptions = [JavaVMOption]( repeating: JavaVMOption(), count: options?.count ?? 1 )
return vmOptions.withUnsafeMutableBufferPointer {
(vmOptionsPtr) in
var vmArgs = JavaVMInitArgs()
vmArgs.version = jint(JNI_VERSION_1_6)
vmArgs.nOptions = jint(options?.count ?? 0)
vmArgs.options = vmOptionsPtr.baseAddress
if let options: [String] = options {
for i in 0..<vmOptionsPtr.count {
options[i].withCString {
(cString) in
vmOptionsPtr[i].optionString = strdup( cString )
}
}
}
var tenv: UnsafeMutablePointer<JNIEnv?>?
if withPointerToRawPointer(to: &tenv, {
JNI_CreateJavaVM( &self.jvm, $0, &vmArgs )
} ) != jint(JNI_OK) {
report( "JNI_CreateJavaVM failed", file, line )
return false
}
if pthread_setspecific( JNICore.envVarKey, tenv ) != 0 {
JNI.report( "Could not set pthread specific tenv" )
}
self.api = self.env!.pointee!.pointee
return true
}
#endif
}
private func withPointerToRawPointer<T, Result>(to arg: inout T, _ body: @escaping (UnsafeMutablePointer<UnsafeMutableRawPointer?>) throws -> Result) rethrows -> Result {
return try withUnsafeMutablePointer(to: &arg) {
try $0.withMemoryRebound(to: UnsafeMutableRawPointer?.self, capacity: 1) {
try body( $0 )
}
}
}
open func GetEnv() -> UnsafeMutablePointer<JNIEnv?>? {
var tenv: UnsafeMutablePointer<JNIEnv?>?
if withPointerToRawPointer(to: &tenv, {
JNI.jvm?.pointee?.pointee.GetEnv( JNI.jvm, $0, jint(JNI_VERSION_1_6 ) )
} ) != jint(JNI_OK) {
report( "Unable to get initial JNIEnv" )
}
return tenv
}
fileprivate let initLock = NSLock()
private func autoInit() {
initLock.lock()
if jvm == nil && !initJVM() {
report( "Auto JVM init failed" )
}
initLock.unlock()
}
open func background( closure: @escaping () -> () ) {
autoInit()
DispatchQueue.global(qos: .default).async {
closure()
}
}
public func run() {
RunLoop.main.run(until: Date.distantFuture)
}
private var loadClassMethodID: jmethodID?
open func FindClass( _ name: UnsafePointer<Int8>, _ file: StaticString = #file, _ line: Int = #line ) -> jclass? {
autoInit()
ExceptionReset()
var clazz: jclass?
if classLoader == nil {
clazz = api.FindClass( env, name )
}
else {
var locals = [jobject]()
var args = [jvalue(l: String(cString: name).localJavaObject(&locals))]
clazz = JNIMethod.CallObjectMethod(object: classLoader,
methodName: "loadClass",
methodSig: "(Ljava/lang/String;)Ljava/lang/Class;",
methodCache: &loadClassMethodID,
args: &args,
locals: &locals)
}
if clazz == nil {
report( "Could not find class \(String( cString: name ))", file, line )
if strncmp( name, "org/swiftjava/", 14 ) == 0 {
report( "\n\nLooking for a swiftjava proxy class required for event listeners and Runnable's to work.\n" +
"Have you copied https://github.com/SwiftJava/SwiftJava/blob/master/swiftjava.jar to ~/.swiftjava.jar " +
"and/or set the CLASSPATH environment variable?\n" )
}
}
return clazz
}
open func CachedFindClass( _ name: UnsafePointer<Int8>, _ classCache: UnsafeMutablePointer<jclass?>,
_ file: StaticString = #file, _ line: Int = #line ) {
if classCache.pointee == nil, let clazz: jclass = FindClass( name, file, line ) {
classCache.pointee = api.NewGlobalRef( env, clazz )
api.DeleteLocalRef( env, clazz )
}
}
open func GetObjectClass( _ object: jobject?, _ locals: UnsafeMutablePointer<[jobject]>,
_ file: StaticString = #file, _ line: Int = #line ) -> jclass? {
ExceptionReset()
if object == nil {
report( "GetObjectClass with nil object", file, line )
}
let clazz: jclass? = api.GetObjectClass( env, object )
if clazz == nil {
report( "GetObjectClass returns nil class", file, line )
}
else {
locals.pointee.append( clazz! )
}
return clazz
}
private static var java_lang_ObjectClass: jclass?
open func NewObjectArray( _ count: Int, _ array: [jobject?]?, _ locals: UnsafeMutablePointer<[jobject]>, _ file: StaticString = #file, _ line: Int = #line ) -> jobjectArray? {
CachedFindClass( "java/lang/Object", &JNICore.java_lang_ObjectClass, file, line )
var arrayClass: jclass? = JNICore.java_lang_ObjectClass
if array?.count != 0 {
arrayClass = JNI.GetObjectClass( array![0], locals )
}
else {
#if os(Android)
return nil
#endif
}
let array: jobjectArray? = api.NewObjectArray( env, jsize(count), arrayClass, nil )
if array == nil {
report( "Could not create array", file, line )
}
return array
}
open func DeleteLocalRef( _ local: jobject? ) {
if local != nil {
api.DeleteLocalRef( env, local )
}
}
private var thrownCache = [pthread_t: jthrowable]()
private let thrownLock = NSLock()
open func check<T>( _ result: T, _ locals: UnsafeMutablePointer<[jobject]>, removeLast: Bool = false, _ file: StaticString = #file, _ line: Int = #line ) -> T {
if removeLast && locals.pointee.count != 0 {
locals.pointee.removeLast()
}
for local in locals.pointee {
DeleteLocalRef( local )
}
if api.ExceptionCheck( env ) != 0, let throwable: jthrowable = api.ExceptionOccurred( env ) {
report( "Exception occured", file, line )
thrownLock.lock()
thrownCache[pthread_self()] = throwable
thrownLock.unlock()
api.ExceptionClear( env )
}
return result
}
open func ExceptionCheck() -> jthrowable? {
let currentThread: pthread_t = pthread_self()
if let throwable: jthrowable = thrownCache[currentThread] {
thrownLock.lock()
thrownCache.removeValue(forKey: currentThread)
thrownLock.unlock()
return throwable
}
return nil
}
open func ExceptionReset() {
if let throwable: jthrowable = ExceptionCheck() {
report( "Left over exception" )
Throwable( javaObject: throwable ).printStackTrace()
}
}
}
extension JavaClass {
public convenience init(loading className: String) {
let clazz = JNI.FindClass( className.replacingOccurrences(of: ".", with: "/") )
self.init( javaObject: clazz )
JNI.DeleteLocalRef( clazz )
}
}