From d8c8be4db8773cce105fb09c396cf8ddf92663ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Kohlschu=CC=88tter?= Date: Mon, 8 Jul 2024 17:53:33 +0200 Subject: [PATCH] native: Workaround for MonitorEnter with pending exception Android doesn't like it when we call MonitorEnter with an exception pending. --- junixsocket-native/src/main/c/filedescriptors.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/junixsocket-native/src/main/c/filedescriptors.c b/junixsocket-native/src/main/c/filedescriptors.c index 37a0b2d66..f2208a669 100644 --- a/junixsocket-native/src/main/c/filedescriptors.c +++ b/junixsocket-native/src/main/c/filedescriptors.c @@ -234,6 +234,13 @@ int _closeFd(JNIEnv * env, jobject fd, int handle) return ret; } + // Android doesn't like it when we call MonitorEnter on a pending exception. + // Temporarily hold on to that exception, and throw again afterwards. + jthrowable throwable = (*env)->ExceptionOccurred(env); + if(throwable != NULL) { + (*env)->ExceptionClear(env); + } + (*env)->MonitorEnter(env, fd); int fdHandle = _getFD(env, fd); _initFD(env, fd, -1); @@ -243,6 +250,10 @@ int _closeFd(JNIEnv * env, jobject fd, int handle) #endif (*env)->MonitorExit(env, fd); + if(throwable != NULL) { + (*env)->Throw(env, throwable); + } + #if defined(_WIN32) jboolean isSocket; if(handleWin > 0) {