Added functions to attach/detach native threads to the JVM
[strongswan.git] / src / frontends / android / jni / libandroidbridge / android_jni.c
1 /*
2 * Copyright (C) 2012 Tobias Brunner
3 * Copyright (C) 2012 Giuliano Grassi
4 * Copyright (C) 2012 Ralf Sager
5 * Hochschule fuer Technik Rapperswil
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 */
17
18 #include "android_jni.h"
19
20 #include <library.h>
21 #include <threading/thread_value.h>
22
23 /**
24 * JVM
25 */
26 static JavaVM *android_jvm;
27
28 jclass *android_charonvpnservice_class;
29
30 /**
31 * Thread-local variable. Only used because of the destructor
32 */
33 static thread_value_t *androidjni_threadlocal;
34
35 /**
36 * Thread-local destructor to ensure that a native thread is detached
37 * from the JVM even if androidjni_detach_thread() is not called.
38 */
39 static void attached_thread_cleanup(void *arg)
40 {
41 (*android_jvm)->DetachCurrentThread(android_jvm);
42 }
43
44 /*
45 * Described in header
46 */
47 void androidjni_attach_thread(JNIEnv **env)
48 {
49 (*android_jvm)->AttachCurrentThread(android_jvm, env, NULL);
50 /* use a thread-local value with a destructor that automatically detaches
51 * the thread from the JVM before it terminates, if not done manually */
52 androidjni_threadlocal->set(androidjni_threadlocal, (void*)*env);
53 }
54
55 /*
56 * Described in header
57 */
58 void androidjni_detach_thread()
59 {
60 androidjni_threadlocal->set(androidjni_threadlocal, NULL);
61 (*android_jvm)->DetachCurrentThread(android_jvm);
62 }
63
64 /**
65 * Called when this library is loaded by the JVM
66 */
67 jint JNI_OnLoad(JavaVM *vm, void *reserved)
68 {
69 JNIEnv *env;
70
71 android_jvm = vm;
72
73 if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)
74 {
75 return -1;
76 }
77
78 androidjni_threadlocal = thread_value_create(attached_thread_cleanup);
79
80 android_charonvpnservice_class =
81 (*env)->NewGlobalRef(env, (*env)->FindClass(env,
82 JNI_PACKAGE_STRING "/CharonVpnService"));
83
84 return JNI_VERSION_1_6;
85 }
86
87 /**
88 * Called when this library is unloaded by the JVM
89 */
90 void JNI_OnUnload(JavaVM *vm, void *reserved)
91 {
92 androidjni_threadlocal->destroy(androidjni_threadlocal);
93 }
94