From a4ea72cb9065e0728e290586b62c67d91899e0f8 Mon Sep 17 00:00:00 2001 From: abduznik <85239936+abduznik@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:29:51 +0300 Subject: [PATCH] Terminal: release createSubprocess's JNI local references, and the cwd chars against cwd (#527) Fix JNI local reference leak in createSubprocess The argv and envp loops took one local reference per element from GetObjectArrayElement and never released it, so the references piled up until the native call returned. ART aborts the process at 512 local references ("local reference table overflow"), and both loops share the table, so a long argument list plus a large environment could hit it. Delete each element's local reference once its chars are copied and released, after ReleaseStringUTFChars since the chars depend on the string. Also release the cwd chars against cwd rather than cmd; the call passed the wrong jstring. Adds a host-side test that runs termux.c against a mock JNIEnv that counts local references and checks release pairing. It needs a jni.h (JNI_INCLUDE, JAVA_HOME or the NDK) and skips without one. Fixes #507 --- app/src/main/cpp/termux/termux.c | 4 +- tools/tests/termux_jni_harness.c | 113 +++++++++++++++++++++++++++++++ tools/tests/test_termux_jni.py | 79 +++++++++++++++++++++ 3 files changed, 195 insertions(+), 1 deletion(-) create mode 100644 tools/tests/termux_jni_harness.c create mode 100644 tools/tests/test_termux_jni.py diff --git a/app/src/main/cpp/termux/termux.c b/app/src/main/cpp/termux/termux.c index 195098169f..7d4f86e31f 100644 --- a/app/src/main/cpp/termux/termux.c +++ b/app/src/main/cpp/termux/termux.c @@ -136,6 +136,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess( if (!arg_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for argv"); argv[i] = strdup(arg_utf8); (*env)->ReleaseStringUTFChars(env, arg_java_string, arg_utf8); + (*env)->DeleteLocalRef(env, arg_java_string); } argv[size] = NULL; } @@ -151,6 +152,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess( if (!env_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for env"); envp[i] = strdup(env_utf8); (*env)->ReleaseStringUTFChars(env, env_java_string, env_utf8); + (*env)->DeleteLocalRef(env, env_java_string); } envp[size] = NULL; } @@ -160,7 +162,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess( char const* cmd_utf8 = (*env)->GetStringUTFChars(env, cmd, NULL); int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns); (*env)->ReleaseStringUTFChars(env, cmd, cmd_utf8); - (*env)->ReleaseStringUTFChars(env, cmd, cmd_cwd); + (*env)->ReleaseStringUTFChars(env, cwd, cmd_cwd); if (argv) { for (char** tmp = argv; *tmp; ++tmp) free(*tmp); diff --git a/tools/tests/termux_jni_harness.c b/tools/tests/termux_jni_harness.c new file mode 100644 index 0000000000..66dc923c8b --- /dev/null +++ b/tools/tests/termux_jni_harness.c @@ -0,0 +1,113 @@ +// Drives Java_com_termux_terminal_JNI_createSubprocess against a mock JNIEnv that tracks local +// references the way ART does, so the JNI hygiene of app/src/main/cpp/termux/termux.c can be +// checked on the host. Built and run by tools/tests/test_termux_jni.py. +#include +#include +#include + +#include "termux.c" + +#define LOCAL_REF_LIMIT 512 + +static int live_refs; +static int peak_refs; +static int overflowed; +static int mismatched_releases; +static int unreleased_chars; + +typedef struct { const void* owner; char* chars; } Pinned; +static Pinned pinned[8]; + +static jsize mock_array_length(JNIEnv* TERMUX_UNUSED(env), jarray array) +{ + return *(jsize*) array; +} + +static jobject mock_get_element(JNIEnv* TERMUX_UNUSED(env), jobjectArray TERMUX_UNUSED(array), jsize TERMUX_UNUSED(index)) +{ + if (++live_refs > peak_refs) peak_refs = live_refs; + // ART aborts the process here: "local reference table overflow (max=512)". + if (live_refs > LOCAL_REF_LIMIT) overflowed = 1; + return (jobject) malloc(1); +} + +static void mock_delete_local_ref(JNIEnv* TERMUX_UNUSED(env), jobject ref) +{ + live_refs--; + free(ref); +} + +static const char* mock_get_utf(JNIEnv* TERMUX_UNUSED(env), jstring string, jboolean* TERMUX_UNUSED(copy)) +{ + for (size_t i = 0; i < sizeof(pinned) / sizeof(pinned[0]); i++) { + if (pinned[i].owner == NULL) { + pinned[i].owner = string; + pinned[i].chars = strdup("x"); + return pinned[i].chars; + } + } + abort(); +} + +static void mock_release_utf(JNIEnv* TERMUX_UNUSED(env), jstring string, const char* chars) +{ + for (size_t i = 0; i < sizeof(pinned) / sizeof(pinned[0]); i++) { + if (pinned[i].owner != NULL && pinned[i].chars == chars) { + // Releasing chars against some other string is a JNI contract violation. + if (pinned[i].owner != string) mismatched_releases++; + free(pinned[i].chars); + pinned[i].owner = NULL; + return; + } + } + mismatched_releases++; +} + +static jclass mock_find_class(JNIEnv* TERMUX_UNUSED(env), const char* TERMUX_UNUSED(name)) { return NULL; } +static jint mock_throw_new(JNIEnv* TERMUX_UNUSED(env), jclass TERMUX_UNUSED(c), const char* message) +{ + fprintf(stderr, "thrown: %s\n", message); + return 0; +} + +static void* mock_get_critical(JNIEnv* TERMUX_UNUSED(env), jarray array, jboolean* TERMUX_UNUSED(copy)) +{ + return array; +} + +static void mock_release_critical(JNIEnv* TERMUX_UNUSED(env), jarray TERMUX_UNUSED(array), void* TERMUX_UNUSED(p), jint TERMUX_UNUSED(mode)) {} + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + jsize arg_count = atoi(argv[1]); + jsize env_count = atoi(argv[2]); + + // The struct is JNINativeInterface in the NDK's header and JNINativeInterface_ in the JDK's. + __typeof__(**(JNIEnv*) 0) table = { + .GetArrayLength = mock_array_length, + .GetObjectArrayElement = mock_get_element, + .DeleteLocalRef = mock_delete_local_ref, + .GetStringUTFChars = mock_get_utf, + .ReleaseStringUTFChars = mock_release_utf, + .FindClass = mock_find_class, + .ThrowNew = mock_throw_new, + .GetPrimitiveArrayCritical = mock_get_critical, + .ReleasePrimitiveArrayCritical = mock_release_critical, + }; + const __typeof__(table)* env = &table; + + // Arrays are modelled as their length; the caller's own references are not counted. + jsize args = arg_count, envs = env_count; + jint pid_slot[1] = {0}; + jstring cmd = (jstring) "cmd", cwd = (jstring) "cwd"; + + Java_com_termux_terminal_JNI_createSubprocess((JNIEnv*) &env, NULL, cmd, cwd, + arg_count ? (jobjectArray) &args : NULL, env_count ? (jobjectArray) &envs : NULL, + (jintArray) pid_slot, 24, 80); + + for (size_t i = 0; i < sizeof(pinned) / sizeof(pinned[0]); i++) if (pinned[i].owner) unreleased_chars++; + printf("peak_refs=%d live_refs=%d overflowed=%d mismatched_releases=%d unreleased_chars=%d\n", + peak_refs, live_refs, overflowed, mismatched_releases, unreleased_chars); + return 0; +} diff --git a/tools/tests/test_termux_jni.py b/tools/tests/test_termux_jni.py new file mode 100644 index 0000000000..0841140060 --- /dev/null +++ b/tools/tests/test_termux_jni.py @@ -0,0 +1,79 @@ +import glob +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +TESTS = Path(__file__).resolve().parent +TERMUX_DIR = TESTS.parents[1] / "app/src/main/cpp/termux" + + +def jni_include_dir(): + """A directory holding jni.h: JNI_INCLUDE, then the JDK, then the Android NDK.""" + candidates = [os.environ.get("JNI_INCLUDE")] + java_home = os.environ.get("JAVA_HOME") + if java_home: + candidates.append(os.path.join(java_home, "include")) + candidates += glob.glob("/usr/lib/jvm/*/include") + for var in ("ANDROID_NDK_LATEST_HOME", "ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "ANDROID_NDK"): + ndk = os.environ.get(var) + if ndk: + candidates += glob.glob(os.path.join(ndk, "toolchains/llvm/prebuilt/*/sysroot/usr/include")) + for candidate in candidates: + if candidate and os.path.isfile(os.path.join(candidate, "jni.h")): + return candidate + return None + + +def include_flags(): + """-I flags for jni.h, plus the JDK's per-platform directory that holds jni_md.h.""" + base = jni_include_dir() + flags = ["-I", base] + for sub in glob.glob(os.path.join(base, "*")): + if os.path.isfile(os.path.join(sub, "jni_md.h")): + flags += ["-I", sub] + return flags + + +@unittest.skipUnless(shutil.which("cc"), "needs a C compiler") +@unittest.skipUnless(jni_include_dir(), "needs jni.h (set JNI_INCLUDE, JAVA_HOME or ANDROID_NDK_HOME)") +class TermuxJniTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.addClassCleanup(cls.tmp.cleanup) + cls.binary = os.path.join(cls.tmp.name, "termux_jni_harness") + subprocess.run( + ["cc", "-std=gnu11", "-D_GNU_SOURCE", "-Wall", *include_flags(), "-I", str(TERMUX_DIR), + str(TESTS / "termux_jni_harness.c"), "-o", cls.binary], + check=True, capture_output=True, text=True) + + def run_harness(self, args, envs): + result = subprocess.run([self.binary, str(args), str(envs)], + capture_output=True, text=True, timeout=30) + self.assertEqual(result.returncode, 0, result.stderr) + line = next(l for l in result.stdout.splitlines() if l.startswith("peak_refs=")) + return {key: int(value) for key, value in re.findall(r"(\w+)=(\d+)", line)} + + def test_a_long_argv_and_environment_stay_under_the_local_reference_limit(self): + # 300 + 300 is under 512 for each loop on its own but over it together, as the issue says: + # ART aborts with "local reference table overflow (max=512)". + stats = self.run_harness(300, 300) + self.assertEqual(stats["overflowed"], 0, stats) + + def test_every_element_reference_is_released(self): + stats = self.run_harness(8, 8) + self.assertEqual(stats["live_refs"], 0, stats) + self.assertLessEqual(stats["peak_refs"], 1, stats) + + def test_utf_chars_are_released_against_the_string_they_came_from(self): + stats = self.run_harness(1, 1) + self.assertEqual(stats["mismatched_releases"], 0, stats) + self.assertEqual(stats["unreleased_chars"], 0, stats) + + +if __name__ == "__main__": + unittest.main()