Skip to content

Commit

Permalink
Avoid static state
Browse files Browse the repository at this point in the history
Motivation:

When statically compiled, the same netty-jni-util may be used by
multiple separate JNI libraries. In this situation there is only one
copy of static variables, so it is only safe to use static variables in
cases where they can safely be reused. That's not the case for the
current staticPackagePrefix.

Modifications:

Force the caller to manage the static state, which can be unique per
usage.

Result:

Static compilation is available again for JNI libraries that supported
static compilation before depending on netty-jni-util. Fixes netty#5.
  • Loading branch information
ejona86 committed Mar 24, 2021
1 parent 9e391e1 commit ce64471
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 16 deletions.
18 changes: 4 additions & 14 deletions src/main/c/netty_jni_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@
#include <string.h>
#include "netty_jni_util.h"

static char* staticPackagePrefix;

void netty_jni_util_free_dynamic_methods_table(JNINativeMethod* dynamicMethods, jint fixedMethodTableSize, jint fullMethodTableSize) {
if (dynamicMethods != NULL) {
jint i = fixedMethodTableSize;
Expand Down Expand Up @@ -463,25 +461,17 @@ jint netty_jni_util_JNI_OnLoad(JavaVM* vm, void* reserved, const char* libname,
#endif /* NETTY_JNI_UTIL_BUILD_STATIC */

jint ret = load_function(env, packagePrefix);
if (ret == JNI_ERR) {
free(packagePrefix);
staticPackagePrefix = NULL;
} else {
// This will be freed when we unload.
staticPackagePrefix = packagePrefix;
}
free(packagePrefix);
return ret;
}

void netty_jni_util_JNI_OnUnload(JavaVM* vm, void* reserved, void (*unload_function)(JNIEnv*, const char*)) {
void netty_jni_util_JNI_OnUnload(JavaVM* vm, void* reserved, void (*unload_function)(JNIEnv*)) {
JNIEnv* env = NULL;
if ((*vm)->GetEnv(vm, (void**) &env, NETTY_JNI_UTIL_JNI_VERSION) != JNI_OK) {
fprintf(stderr, "FATAL: JNI version missmatch");
fflush(stderr);
// Something is wrong but nothing we can do about this :(
return;
}
unload_function(env, staticPackagePrefix);
free(staticPackagePrefix);
staticPackagePrefix = NULL;
}
unload_function(env);
}
4 changes: 2 additions & 2 deletions src/main/c/netty_jni_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,6 @@ jint netty_jni_util_JNI_OnLoad(JavaVM* vm, void* reserved, const char* libname,
/**
* Function should be called when the native library is unloaded
*/
void netty_jni_util_JNI_OnUnload(JavaVM* vm, void* reserved, void (*unload_function)(JNIEnv*, const char*));
void netty_jni_util_JNI_OnUnload(JavaVM* vm, void* reserved, void (*unload_function)(JNIEnv*));

#endif /* NETTY_JNI_UTIL_H_ */
#endif /* NETTY_JNI_UTIL_H_ */

0 comments on commit ce64471

Please sign in to comment.