From 1a006d6f06acb09c54e38e4b16e175b914e5d3d7 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Fri, 9 Mar 2018 19:25:51 -0800 Subject: [PATCH] misc: add jni helpers --- misc/jni.c | 429 +++++++++++++++++++++++++++++++++++++++++++++++ misc/jni.h | 161 ++++++++++++++++++ wscript_build.py | 1 + 3 files changed, 591 insertions(+) create mode 100644 misc/jni.c create mode 100644 misc/jni.h diff --git a/misc/jni.c b/misc/jni.c new file mode 100644 index 0000000000..3f76f379cb --- /dev/null +++ b/misc/jni.c @@ -0,0 +1,429 @@ +/* + * JNI utility functions + * + * Copyright (c) 2015-2016 Matthieu Bouron + * + * This file is part of mpv. + * + * mpv is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * mpv is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with mpv. If not, see . + */ + +#include +#include +#include +#include +#include + +#include "jni.h" + +static JavaVM *java_vm; +static pthread_key_t current_env; +static pthread_once_t once = PTHREAD_ONCE_INIT; +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + +static void jni_detach_env(void *data) +{ + if (java_vm) { + (*java_vm)->DetachCurrentThread(java_vm); + } +} + +static void jni_create_pthread_key(void) +{ + pthread_key_create(¤t_env, jni_detach_env); +} + +JNIEnv *mp_jni_get_env(struct mp_log *log) +{ + int ret = 0; + JNIEnv *env = NULL; + + pthread_mutex_lock(&lock); + if (java_vm == NULL) { + java_vm = av_jni_get_java_vm(NULL); + } + + if (!java_vm) { + mp_err(log, "No Java virtual machine has been registered\n"); + goto done; + } + + pthread_once(&once, jni_create_pthread_key); + + if ((env = pthread_getspecific(current_env)) != NULL) { + goto done; + } + + ret = (*java_vm)->GetEnv(java_vm, (void **)&env, JNI_VERSION_1_6); + switch(ret) { + case JNI_EDETACHED: + if ((*java_vm)->AttachCurrentThread(java_vm, &env, NULL) != 0) { + mp_err(log, "Failed to attach the JNI environment to the current thread\n"); + env = NULL; + } else { + pthread_setspecific(current_env, env); + } + break; + case JNI_OK: + break; + case JNI_EVERSION: + mp_err(log, "The specified JNI version is not supported\n"); + break; + default: + mp_err(log, "Failed to get the JNI environment attached to this thread\n"); + break; + } + +done: + pthread_mutex_unlock(&lock); + return env; +} + +char *mp_jni_jstring_to_utf_chars(JNIEnv *env, jstring string, struct mp_log *log) +{ + char *ret = NULL; + const char *utf_chars = NULL; + + jboolean copy = 0; + + if (!string) { + return NULL; + } + + utf_chars = (*env)->GetStringUTFChars(env, string, ©); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "String.getStringUTFChars() threw an exception\n"); + return NULL; + } + + ret = av_strdup(utf_chars); + + (*env)->ReleaseStringUTFChars(env, string, utf_chars); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "String.releaseStringUTFChars() threw an exception\n"); + return NULL; + } + + return ret; +} + +jstring mp_jni_utf_chars_to_jstring(JNIEnv *env, const char *utf_chars, struct mp_log *log) +{ + jstring ret; + + ret = (*env)->NewStringUTF(env, utf_chars); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "NewStringUTF() threw an exception\n"); + return NULL; + } + + return ret; +} + +int mp_jni_exception_get_summary(JNIEnv *env, jthrowable exception, char **error, struct mp_log *log) +{ + int ret = 0; + + AVBPrint bp; + + char *name = NULL; + char *message = NULL; + + jclass class_class = NULL; + jmethodID get_name_id = NULL; + + jclass exception_class = NULL; + jmethodID get_message_id = NULL; + + jstring string = NULL; + + av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC); + + exception_class = (*env)->GetObjectClass(env, exception); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "Could not find Throwable class\n"); + ret = -1; + goto done; + } + + class_class = (*env)->GetObjectClass(env, exception_class); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "Could not find Throwable class's class\n"); + ret = -1; + goto done; + } + + get_name_id = (*env)->GetMethodID(env, class_class, "getName", "()Ljava/lang/String;"); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "Could not find method Class.getName()\n"); + ret = -1; + goto done; + } + + string = (*env)->CallObjectMethod(env, exception_class, get_name_id); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "Class.getName() threw an exception\n"); + ret = -1; + goto done; + } + + if (string) { + name = mp_jni_jstring_to_utf_chars(env, string, log); + (*env)->DeleteLocalRef(env, string); + string = NULL; + } + + get_message_id = (*env)->GetMethodID(env, exception_class, "getMessage", "()Ljava/lang/String;"); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "Could not find method java/lang/Throwable.getMessage()\n"); + ret = -1; + goto done; + } + + string = (*env)->CallObjectMethod(env, exception, get_message_id); + if ((*env)->ExceptionCheck(env)) { + (*env)->ExceptionClear(env); + mp_err(log, "Throwable.getMessage() threw an exception\n"); + ret = -1; + goto done; + } + + if (string) { + message = mp_jni_jstring_to_utf_chars(env, string, log); + (*env)->DeleteLocalRef(env, string); + string = NULL; + } + + if (name && message) { + av_bprintf(&bp, "%s: %s", name, message); + } else if (name && !message) { + av_bprintf(&bp, "%s occurred", name); + } else if (!name && message) { + av_bprintf(&bp, "Exception: %s", message); + } else { + mp_warn(log, "Could not retrieve exception name and message\n"); + av_bprintf(&bp, "Exception occurred"); + } + + ret = av_bprint_finalize(&bp, error); +done: + + av_free(name); + av_free(message); + + if (class_class) { + (*env)->DeleteLocalRef(env, class_class); + } + + if (exception_class) { + (*env)->DeleteLocalRef(env, exception_class); + } + + if (string) { + (*env)->DeleteLocalRef(env, string); + } + + return ret; +} + +int mp_jni_exception_check(JNIEnv *env, int logging, struct mp_log *log) +{ + int ret; + + jthrowable exception; + + char *message = NULL; + + if (!(*(env))->ExceptionCheck((env))) { + return 0; + } + + if (!logging) { + (*(env))->ExceptionClear((env)); + return -1; + } + + exception = (*env)->ExceptionOccurred(env); + (*(env))->ExceptionClear((env)); + + if ((ret = mp_jni_exception_get_summary(env, exception, &message, log)) < 0) { + (*env)->DeleteLocalRef(env, exception); + return ret; + } + + (*env)->DeleteLocalRef(env, exception); + + mp_err(log, "%s\n", message); + av_free(message); + + return -1; +} + +int mp_jni_init_jfields(JNIEnv *env, void *jfields, const struct MPJniField *jfields_mapping, int global, struct mp_log *log) +{ + int i, ret = 0; + jclass last_clazz = NULL; + + for (i = 0; jfields_mapping[i].name; i++) { + int mandatory = jfields_mapping[i].mandatory; + enum MPJniFieldType type = jfields_mapping[i].type; + + if (type == MP_JNI_CLASS) { + jclass clazz; + + last_clazz = NULL; + + clazz = (*env)->FindClass(env, jfields_mapping[i].name); + if ((ret = mp_jni_exception_check(env, mandatory, log)) < 0 && mandatory) { + goto done; + } + + last_clazz = *(jclass*)((uint8_t*)jfields + jfields_mapping[i].offset) = + global ? (*env)->NewGlobalRef(env, clazz) : clazz; + + if (global) { + (*env)->DeleteLocalRef(env, clazz); + } + + } else { + + if (!last_clazz) { + ret = -1; + break; + } + + switch(type) { + case MP_JNI_FIELD: { + jfieldID field_id = (*env)->GetFieldID(env, last_clazz, jfields_mapping[i].method, jfields_mapping[i].signature); + if ((ret = mp_jni_exception_check(env, mandatory, log)) < 0 && mandatory) { + goto done; + } + + *(jfieldID*)((uint8_t*)jfields + jfields_mapping[i].offset) = field_id; + break; + } + case MP_JNI_STATIC_FIELD_AS_INT: + case MP_JNI_STATIC_FIELD: { + jfieldID field_id = (*env)->GetStaticFieldID(env, last_clazz, jfields_mapping[i].method, jfields_mapping[i].signature); + if ((ret = mp_jni_exception_check(env, mandatory, log)) < 0 && mandatory) { + goto done; + } + + if (type == MP_JNI_STATIC_FIELD_AS_INT) { + if (field_id) { + jint value = (*env)->GetStaticIntField(env, last_clazz, field_id); + if ((ret = mp_jni_exception_check(env, mandatory, log)) < 0 && mandatory) { + goto done; + } + *(jint*)((uint8_t*)jfields + jfields_mapping[i].offset) = value; + } + } else { + *(jfieldID*)((uint8_t*)jfields + jfields_mapping[i].offset) = field_id; + } + break; + } + case MP_JNI_METHOD: { + jmethodID method_id = (*env)->GetMethodID(env, last_clazz, jfields_mapping[i].method, jfields_mapping[i].signature); + if ((ret = mp_jni_exception_check(env, mandatory, log)) < 0 && mandatory) { + goto done; + } + + *(jmethodID*)((uint8_t*)jfields + jfields_mapping[i].offset) = method_id; + break; + } + case MP_JNI_STATIC_METHOD: { + jmethodID method_id = (*env)->GetStaticMethodID(env, last_clazz, jfields_mapping[i].method, jfields_mapping[i].signature); + if ((ret = mp_jni_exception_check(env, mandatory, log)) < 0 && mandatory) { + goto done; + } + + *(jmethodID*)((uint8_t*)jfields + jfields_mapping[i].offset) = method_id; + break; + } + default: + mp_err(log, "Unknown JNI field type\n"); + ret = -1; + goto done; + } + + ret = 0; + } + } + +done: + if (ret < 0) { + /* reset jfields in case of failure so it does not leak references */ + mp_jni_reset_jfields(env, jfields, jfields_mapping, global, log); + } + + return ret; +} + +int mp_jni_reset_jfields(JNIEnv *env, void *jfields, const struct MPJniField *jfields_mapping, int global, struct mp_log *log) +{ + int i; + + for (i = 0; jfields_mapping[i].name; i++) { + enum MPJniFieldType type = jfields_mapping[i].type; + + switch(type) { + case MP_JNI_CLASS: { + jclass clazz = *(jclass*)((uint8_t*)jfields + jfields_mapping[i].offset); + if (!clazz) + continue; + + if (global) { + (*env)->DeleteGlobalRef(env, clazz); + } else { + (*env)->DeleteLocalRef(env, clazz); + } + + *(jclass*)((uint8_t*)jfields + jfields_mapping[i].offset) = NULL; + break; + } + case MP_JNI_FIELD: { + *(jfieldID*)((uint8_t*)jfields + jfields_mapping[i].offset) = NULL; + break; + } + case MP_JNI_STATIC_FIELD: { + *(jfieldID*)((uint8_t*)jfields + jfields_mapping[i].offset) = NULL; + break; + } + case MP_JNI_STATIC_FIELD_AS_INT: { + *(jint*)((uint8_t*)jfields + jfields_mapping[i].offset) = 0; + break; + } + case MP_JNI_METHOD: { + *(jmethodID*)((uint8_t*)jfields + jfields_mapping[i].offset) = NULL; + break; + } + case MP_JNI_STATIC_METHOD: { + *(jmethodID*)((uint8_t*)jfields + jfields_mapping[i].offset) = NULL; + break; + } + default: + mp_err(log, "Unknown JNI field type\n"); + } + } + + return 0; +} diff --git a/misc/jni.h b/misc/jni.h new file mode 100644 index 0000000000..c9e4c28fe7 --- /dev/null +++ b/misc/jni.h @@ -0,0 +1,161 @@ +/* + * JNI utility functions + * + * Copyright (c) 2015-2016 Matthieu Bouron + * + * This file is part of mpv. + * + * mpv is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * mpv is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with mpv. If not, see . + */ + +#ifndef MP_JNI_H +#define MP_JNI_H + +#include +#include "common/msg.h" + +/* Convenience macros */ +#define MP_JNI_GET_ENV(obj) mp_jni_get_env((obj)->log) +#define MP_JNI_EXCEPTION_CHECK() mp_jni_exception_check(env, 0, NULL) +#define MP_JNI_EXCEPTION_LOG(obj) mp_jni_exception_check(env, 1, (obj)->log) +#define MP_JNI_DO(what, obj, method, ...) (*env)->what(env, obj, method, ##__VA_ARGS__) +#define MP_JNI_NEW(clazz, method, ...) MP_JNI_DO(NewObject, clazz, method, ##__VA_ARGS__) +#define MP_JNI_CALL_INT(obj, method, ...) MP_JNI_DO(CallIntMethod, obj, method, ##__VA_ARGS__) +#define MP_JNI_CALL_BOOL(obj, method, ...) MP_JNI_DO(CallBooleanMethod, obj, method, ##__VA_ARGS__) +#define MP_JNI_CALL_VOID(obj, method, ...) MP_JNI_DO(CallVoidMethod, obj, method, ##__VA_ARGS__) +#define MP_JNI_CALL_STATIC_INT(clazz, method, ...) MP_JNI_DO(CallStaticIntMethod, clazz, method, ##__VA_ARGS__) +#define MP_JNI_CALL_OBJECT(obj, method, ...) MP_JNI_DO(CallObjectMethod, obj, method, ##__VA_ARGS__) +#define MP_JNI_GET_INT(obj, field) MP_JNI_DO(GetIntField, obj, field) +#define MP_JNI_GET_LONG(obj, field) MP_JNI_DO(GetLongField, obj, field) +#define MP_JNI_GET_BOOL(obj, field) MP_JNI_DO(GetBoolField, obj, field) + +/* + * Attach permanently a JNI environment to the current thread and retrieve it. + * + * If successfully attached, the JNI environment will automatically be detached + * at thread destruction. + * + * @param attached pointer to an integer that will be set to 1 if the + * environment has been attached to the current thread or 0 if it is + * already attached. + * @param log context used for logging + * @return the JNI environment on success, NULL otherwise + */ +JNIEnv *mp_jni_get_env(struct mp_log *log); + +/* + * Convert a jstring to its utf characters equivalent. + * + * @param env JNI environment + * @param string Java string to convert + * @param log context used for logging + * @return a pointer to an array of unicode characters on success, NULL + * otherwise + */ +char *mp_jni_jstring_to_utf_chars(JNIEnv *env, jstring string, struct mp_log *log); + +/* + * Convert utf chars to its jstring equivalent. + * + * @param env JNI environment + * @param utf_chars a pointer to an array of unicode characters + * @param log context used for logging + * @return a Java string object on success, NULL otherwise + */ +jstring mp_jni_utf_chars_to_jstring(JNIEnv *env, const char *utf_chars, struct mp_log *log); + +/* + * Extract the error summary from a jthrowable in the form of "className: errorMessage" + * + * @param env JNI environment + * @param exception exception to get the summary from + * @param error address pointing to the error, the value is updated if a + * summary can be extracted + * @param log context used for logging + * @return 0 on success, < 0 otherwise + */ +int mp_jni_exception_get_summary(JNIEnv *env, jthrowable exception, char **error, struct mp_log *log); + +/* + * Check if an exception has occurred,log it using av_log and clear it. + * + * @param env JNI environment + * @param value used to enable logging if an exception has occurred, + * 0 disables logging, != 0 enables logging + * @param log context used for logging + */ +int mp_jni_exception_check(JNIEnv *env, int logging, struct mp_log *log); + +/* + * Jni field type. + */ +enum MPJniFieldType { + + MP_JNI_CLASS, + MP_JNI_FIELD, + MP_JNI_STATIC_FIELD, + MP_JNI_STATIC_FIELD_AS_INT, + MP_JNI_METHOD, + MP_JNI_STATIC_METHOD + +}; + +/* + * Jni field describing a class, a field or a method to be retrieved using + * the mp_jni_init_jfields method. + */ +struct MPJniField { + + const char *name; + const char *method; + const char *signature; + enum MPJniFieldType type; + int offset; + int mandatory; + +}; + +/* + * Retrieve class references, field ids and method ids to an arbitrary structure. + * + * @param env JNI environment + * @param jfields a pointer to an arbitrary structure where the different + * fields are declared and where the MPJNIField mapping table offsets are + * pointing to + * @param jfields_mapping null terminated array of MPJNIFields describing + * the class/field/method to be retrieved + * @param global make the classes references global. It is the caller + * responsibility to properly release global references. + * @param log_ctx context used for logging, can be NULL + * @return 0 on success, < 0 otherwise + */ +int mp_jni_init_jfields(JNIEnv *env, void *jfields, const struct MPJniField *jfields_mapping, int global, struct mp_log *log); + +/* + * Delete class references, field ids and method ids of an arbitrary structure. + * + * @param env JNI environment + * @param jfields a pointer to an arbitrary structure where the different + * fields are declared and where the MPJNIField mapping table offsets are + * pointing to + * @param jfields_mapping null terminated array of MPJNIFields describing + * the class/field/method to be deleted + * @param global treat the classes references as global and delete them + * accordingly + * @param log_ctx context used for logging, can be NULL + * @return 0 on success, < 0 otherwise + */ +int mp_jni_reset_jfields(JNIEnv *env, void *jfields, const struct MPJniField *jfields_mapping, int global, struct mp_log *log); + +#endif diff --git a/wscript_build.py b/wscript_build.py index d9c03fe7f1..3ae0fcfee8 100644 --- a/wscript_build.py +++ b/wscript_build.py @@ -326,6 +326,7 @@ def build(ctx): ( "misc/bstr.c" ), ( "misc/charset_conv.c" ), ( "misc/dispatch.c" ), + ( "misc/jni.c", "android" ), ( "misc/json.c" ), ( "misc/natural_sort.c" ), ( "misc/node.c" ),