forked from SwiftJava/java_swift
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathJNICore.swift
360 lines (309 loc) · 12.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//
// 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
#if canImport(Android)
import Android
#endif
#if canImport(Glibc)
import Glibc
#endif
@_exported import CAndroidNDK
@_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
var result = withUnsafeMutablePointer(to: &jniEnvKey, {
pthread_key_create($0, JNI_DetachCurrentThread)
})
if (result != 0) {
fatalError("Can't pthread_key_create")
}
pthread_setspecific(jniEnvKey, env)
result = withUnsafeMutablePointer(to: &jniFatalMessage, {
pthread_key_create($0, JNI_RemoveFatalMessage)
})
if (result != 0) {
fatalError("Can't pthread_key_create")
}
// 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
let threadClass = JNI.api.FindClass(env, "java/lang/Thread")
let currentThreadMethodID = JNI.api.GetStaticMethodID(env, threadClass, "currentThread", "()Ljava/lang/Thread;")
let getContextClassLoaderMethodID = JNI.api.GetMethodID(env, threadClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;")
let currentThread = JNI.api.CallStaticObjectMethodA(env, threadClass, currentThreadMethodID, nil)
JNI.classLoader = JNI.api.NewGlobalRef(env, JNI.api.CallObjectMethodA(env, currentThread, getContextClassLoaderMethodID, nil))
return jint(JNI_VERSION_1_6)
}
fileprivate class FatalErrorMessage {
let description: String
let file: String
let line: Int
init(description: String, file: String, line: Int) {
self.description = description
self.file = file
self.line = line
}
}
public func JNI_DetachCurrentThread(_ ptr: UnsafeMutableRawPointer?) {
_ = JNI.jvm?.pointee?.pointee.DetachCurrentThread( JNI.jvm )
}
public func JNI_RemoveFatalMessage(_ ptr: UnsafeMutableRawPointer?) {
if let ptr = ptr {
Unmanaged<FatalErrorMessage>.fromOpaque(ptr).release()
}
}
public let JNI = JNICore()
fileprivate var jniEnvKey = pthread_key_t()
fileprivate var jniFatalMessage = pthread_key_t()
open class JNICore {
open var jvm: UnsafeMutablePointer<JavaVM?>?
open var api: JNINativeInterface!
open var classLoader: jclass!
open var threadKey: pid_t { return gettid() }
open var errorLogger: (_ message: String) -> Void = { message in
NSLog(message)
}
open var env: UnsafeMutablePointer<JNIEnv?>? {
if let env: UnsafeMutableRawPointer = pthread_getspecific(jniEnvKey) {
return env.assumingMemoryBound(to: JNIEnv?.self)
}
let env = AttachCurrentThread()
let error = pthread_setspecific(jniEnvKey, env)
if error != 0 {
NSLog("Can't save env to pthread_setspecific")
}
return env
}
open func AttachCurrentThread() -> UnsafeMutablePointer<JNIEnv?>? {
var tenv: UnsafeMutablePointer<JNIEnv?>?
let result = self.jvm?.pointee?.pointee.AttachCurrentThread( self.jvm, &tenv, nil )
if result != jint(JNI_OK) {
report( "Could not attach to background jvm" )
}
return tenv
}
open func report( _ msg: String, _ file: StaticString = #file, _ line: Int = #line ) {
errorLogger( "\(msg) - at \(file):\(line)" )
if let throwable: jthrowable = ExceptionCheck() {
let throwable = Throwable(javaObject: throwable)
let className = throwable.className()
let message = throwable.getMessage()
let stackTrace = throwable.stackTraceString()
errorLogger("\(className): \(message ?? "unavailable")\(stackTrace)")
throwable.printStackTrace()
}
}
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 withUnsafeMutablePointer(to: &vmOptions[0]) {
(vmOptionsPtr) in
var vmArgs = JavaVMInitArgs()
vmArgs.version = jint(JNI_VERSION_1_6)
vmArgs.nOptions = jint(options?.count ?? 0)
vmArgs.options = vmOptionsPtr
if let options: [String] = options {
for i in 0..<options.count {
options[i].withCString {
(cString) in
vmOptions[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
}
self.envCache[threadKey] = 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
}
private func autoInit() {
}
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 locals = [jobject]()
var args = [jvalue(l: String(cString: name).localJavaObject(&locals))]
let clazz: jclass? = 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 = [pid_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 {
if let throwable: jthrowable = api.ExceptionOccurred( env ) {
thrownLock.lock()
thrownCache[threadKey] = throwable
thrownLock.unlock()
api.ExceptionClear(env)
}
}
return result
}
open func ExceptionCheck() -> jthrowable? {
let currentThread: pid_t = threadKey
thrownLock.lock()
defer {
thrownLock.unlock()
}
if let throwable: jthrowable = thrownCache[currentThread] {
thrownCache.removeValue(forKey: currentThread)
return throwable
}
return nil
}
open func ExceptionReset() {
if let throwable: jthrowable = ExceptionCheck() {
errorLogger( "Left over exception" )
let throwable = Throwable(javaObject: throwable)
let className = throwable.className()
let message = throwable.getMessage()
let stackTrace = throwable.stackTraceString()
errorLogger("\(className): \(message ?? "unavailable")\(stackTrace)")
throwable.printStackTrace()
}
}
open func SaveFatalErrorMessage(_ msg: String, _ file: StaticString = #file, _ line: Int = #line) {
let fatalError = FatalErrorMessage(description: msg, file: file.description, line: line)
let ptr = Unmanaged.passRetained(fatalError).toOpaque()
let error = pthread_setspecific(jniFatalMessage, ptr)
if error != 0 {
errorLogger("Can't save fatal message to pthread_setspecific")
}
}
open func RemoveFatalErrorMessage() {
pthread_setspecific(jniFatalMessage, nil)
}
open func GetFatalErrorMessage() -> String? {
guard let ptr: UnsafeMutableRawPointer = pthread_getspecific(jniFatalMessage) else {
return nil
}
let fatalErrorMessage = Unmanaged<FatalErrorMessage>.fromOpaque(ptr).takeUnretainedValue()
return "\(fatalErrorMessage.description) at \(fatalErrorMessage.file):\(fatalErrorMessage.line)"
}
}