Repository navigation
[Java.Interop] Detach lazily attached JNI threads on exit - #13801
simonrozsival wants to merge 17 commits into
Conversation
Context: #10316 Managed workers that use JNI can exit while still attached to ART, causing the VM to abort. Java.Interop bypassed the CoreCLR pthread cleanup, and NativeAOT did not initialize it. Reuse existing attachments without taking ownership, and register the native pthread destructor for threads attached by Java.Interop. Share that cleanup with NativeAOT. Validation: * `dotnet test tests/Java.Interop-ThreadAttachment-Tests/Java.Interop-ThreadAttachment-Tests.csproj --no-restore -v minimal -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false` — passed (6 tests). * The documented native pthread probe — passed (5 cases). * CoreCLR and NativeAOT device tests and the full SDK build remain pending. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
External detach and reattach can replace a runtime-owned JNI attachment without clearing its pthread cleanup key. Java.Interop supports reentry with a current environment, but restoring that cached environment does not restore cleanup ownership. Document the remaining limitation rather than presenting the thread-exit fix as complete. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Remove the standalone fake-JVM tests and native probe, which duplicate implementation details outside the established runtime test suites. Preserve the investigation repros in session artifacts and keep the focused device coverage. The existing managed-thread test already exercises JNI use on a new managed thread. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Pass the native thread-detach registration callback through creation options instead of storing it globally. Initialize those options directly in both Android startup paths and avoid a redundant GetEnv call during runtime construction. Remove the questionable detached-thread test helper. The pthread cleanup still has unresolved ownership and destructor-ordering hazards; this remains a candidate rather than a complete fix. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The runtime's pthread key is created in JNI_OnLoad, so its destructor
usually runs before the destructors of keys that native libraries create
later. Detaching in the first round pulled the JNI attachment out from
under library destructors that still need it: GetEnv returned
JNI_EDETACHED, a cached JNIEnv* tripped CheckJNI ("making JNI calls
without being attached"), and a library that had re-attached the thread
lost its own attachment before its cleanup ran.
Re-arm the key until the last of the PTHREAD_DESTRUCTOR_ITERATIONS rounds
and only then detach, so ordinary destructors run while the thread is
still attached.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
The change breaks construction for existing external JniRuntime subclasses and can leak JNI thread attachments when destructor cleanup rounds are reset.
3 open issues
What changed in this PR
Extends the native host’s thread-exit cleanup to threads lazily attached by Java.Interop, addressing leaked Java threads and ART thread-ID exhaustion under CoreCLR and NativeAOT.
Changes:
- Adds a required per-runtime cleanup callback, registered only when Java.Interop creates the attachment.
- Defers detachment until the final pthread destructor round to accommodate native-library cleanup.
- Integrates the shared cleanup implementation into NativeAOT and simplifies runtime option construction.
| File | Description |
|---|---|
src/native/nativeaot/host/host.cc |
Initializes shared cleanup and supplies the callback. |
src/native/nativeaot/host/CMakeLists.txt |
Compiles the shared cleanup implementation for NativeAOT. |
src/native/native.targets |
Tracks the shared source as a NativeAOT build input. |
src/native/common/include/runtime-base/runtime-environment.hh |
Exposes cleanup registration to both hosts. |
src/native/common/include/managed-interface.hh |
Adds the callback to the native initialization descriptor and updates layout checks. |
src/native/clr/host/runtime-environment.cc |
Defers detachment through successive destructor rounds. |
src/native/clr/host/host.cc |
Supplies the cleanup callback during CoreCLR initialization. |
src/Mono.Android/Android.Runtime/JNIEnvInit.cs |
Mirrors the descriptor field and forwards the callback. |
src/Mono.Android/Android.Runtime/AndroidRuntime.cs |
Configures the callback directly through CreationOptions. |
src/Microsoft.Android.Runtime.NativeAOT/Java.Interop/JreRuntime.cs |
Removes the NativeAOT-specific options wrapper. |
src/Microsoft.Android.Runtime.NativeAOT/Android.Runtime.NativeAOT/JavaInteropRuntime.cs |
Passes the native callback into runtime construction. |
src/Java.Interop/PublicAPI.Unshipped.txt |
Records the new callback property. |
src/Java.Interop/Java.Interop/JniRuntime.cs |
Validates and stores the callback, checks attachment ownership, and registers cleanup. |
Review effort: Balanced
|
Reviewed as PeppersMuse. No issues found in the change itself. What I checked:
On Copilot's open points: the required callback is a deliberate, disclosed fail-fast choice (the description states the constructor throws when it is missing and that no in-tree code constructs a |
…ous-waddle # Conflicts: # src/Microsoft.Android.Runtime.NativeAOT/Android.Runtime.NativeAOT/JavaInteropRuntime.cs # src/Microsoft.Android.Runtime.NativeAOT/Java.Interop/JreRuntime.cs # src/Mono.Android/Android.Runtime/AndroidRuntime.cs
JniRuntime.CreationOptions and the JniRuntime constructor are shipped APIs, so requiring the new callback would make existing JniRuntime subclasses throw during construction. Without a callback, threads that the runtime attaches stay attached when they exit, as before. The Android hosts always set it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
If another key destructor detaches the thread and something re-attaches it through RuntimeEnvironment::get_jnienv() or Java.Interop, register_thread_detach() reset the stored round to 1. The remaining destructor rounds then ended before the last one, so the new attachment leaked. Keep an existing non-null round instead. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
ManagedThreadIsDetachedOnExit checks that a managed thread attached by Java.Interop is no longer alive in the VM after it exits. NativeDestructorCanUseJniOnThreadExit checks that a native pthread key destructor created after the runtime's key can still use JNI while the thread exits. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
NativeDestructorCanUseJniOnThreadExit covered a best-effort ordering scenario we constructed ourselves, not one anyone reported, so drop it and its reuse-threads.c helpers. Also drop the check that the worker starts detached: it pinned today's lazy attachment, and ManagedThreadIsDetachedOnExit only needs to assert that the thread is no longer alive in the VM after it exits. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Fixed polling limits can flake on slow devices. Make ManagedThreadIsDetachedOnExit async with a cooperative [Timeout], and wait for the worker and its detach with Task.Delay on TestContext.CancellationToken. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
BuildNativeAotWithoutCPlusPlusArchives failed on every ABI because it forbids any RuntimeEnvironment symbol in a NativeAOT app, and the NativeAOT host now links runtime-environment.cc for thread-exit detachment. That code needs a cached JavaVM*, since a pthread key destructor has no JNIEnv* to get one from. Compile get_jnienv(), which attaches the current thread and is only used by CoreCLR's DsoLoader, only for CoreCLR, following the XA_HOST_NATIVEAOT pattern in binary-blob-loader. Narrow the test to that function, which keeps its intent: NativeAOT startup uses the JNIEnv* it is given rather than obtaining one from a cached VM. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Compile the NativeAOT host archive with -ffunction-sections and -fdata-sections. The app link already passes --gc-sections, but with one section per object file it kept every function of each host object it needed, including CoreCLR-only code such as RuntimeEnvironment::get_jnienv() from the shared runtime-environment.cc. Per-function sections let the linker drop it without #if guards, so revert them. In an arm64 Release sample app, the link now drops 7 unused host functions and the stripped library shrinks by 1,304 bytes; the gzipped size is unchanged. The NativeAOT app still exports only JNI_OnLoad, JNI_OnUnload and the JavaInteropRuntime init entry point, so no hidden host function is looked up at runtime. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
… test The NativeAOT host now links runtime-environment.cc on purpose for thread-exit detachment, and --gc-sections already drops the unused get_jnienv(), so the assertion no longer guards anything interesting. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 14 changed files and the affected JNI attach/detach paths, including CLR and NativeAOT callback wiring, struct layout, thread-local cleanup, and the optional callback compatibility fix. The last-round cleanup and documented best-effort teardown tradeoffs are consistent with the implementation. No blocking issues found.
…ous-waddle # Conflicts: # src/Mono.Android/Android.Runtime/JNIEnvInit.cs


Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
0d8fddcf12d1f7ab4931a77b9bf57791eead657c↑ All 23
NativeAotBuildTestspass locally, including the test that failed in CI, on 3 ABIs.↑ The 7 host functions dropped by
--gc-sectionsare unused or inlined; the app exports only its JNI entry points.↑ ART probe on both runtimes: library destructors keep JNI and no Java threads leak.
↓ CI on this revision is queued; the earlier build 1702358 failed only on the NativeAOT link test fixed since.
↓ Only an API 35 arm64 emulator was used; no physical devices or other API levels.
↓ A destructor that also re-arms itself until the last round still runs after the detach (documented).
Out of internal thread idsat about 65,500.↑ The explicit-detach control left 0 threads, isolating the missing detach.
↑ The same demo on this branch leaves 0 threads.
↓ No crash report from a real app is linked to this leak.
Context: https://developer.android.com/ndk/guides/jni-tips#threads
Context: #10316
Context: #13358
A managed thread that calls into Java is attached to the JavaVM lazily by Java.Interop (
JniEnvironment→JniRuntime._AttachCurrentThread()), and nothing ever detaches it. JNI requires a thread attached withAttachCurrentThread()to callDetachCurrentThread()before it exits. On API 24+, ART doesn't abort when an attached thread exits, but it doesn't clean up either: the thread stays registered with the VM, holding itsjava.lang.Thread, native memory and one of ART's internal thread IDs. Apps that keep creating short-lived threads that touch Java eventually run out of thread IDs and abort:Reproducing the leak
A standalone CoreCLR app starts one short-lived managed thread at a time and waits for it with
Join(), so there is never more than one worker alive. Each worker makes an ordinary JNI call, which triggers Java.Interop's lazy attachment, and a tiny Java helper renames the worker'sjava.lang.Threadso it can be counted afterwards:Every 500 workers the app samples the named-worker count, live Linux threads (
/proc/self/status), RSS, native heap, Java heap and managed heap, after running managed and Java GC. Each mode runs in a fresh process:DetachCurrentThread()on the worker.Before this change (.NET 11.0.100-rc.3 CoreCLR, API 35 arm64 emulator, 5,000 workers, mean of two runs per mode):
Every finished worker is still registered with ART even though only 30 Linux threads are alive. With 70,000 workers requested, the last successful sample was at 65,500 workers (+528 MiB native heap), after which ART aborted inside
AttachCurrentThread()withOut of internal thread ids; that's the stack above. The baseline used the .NET 11 RC 3 SDK; Java.Interop's attach path onmaindoesn't detach either.With this change, built from this branch, on the same emulator (5,000 workers, one run per mode):
Detaching from a pthread key destructor
Android's JNI guidance is to detach from a
pthread_key_create()destructor, which runs on the exiting thread itself. The native host already has such a key: #13358 addedRuntimeEnvironment::register_thread_detach()for threads the host attaches throughRuntimeEnvironment::get_jnienv(). Java.Interop now uses the same key for the threads it attaches:JniRuntime._AttachCurrentThread()callsGetEnv()first. Only when that returnsJNI_EDETACHEDand the subsequentAttachCurrentThread()succeeds does it register the cleanup, so an attachment made by someone else is never claimed.&RuntimeEnvironment::register_thread_detachto managed code throughJnienvInitializeArgs.registerThreadDetach. It reaches Java.Interop as a new, optionalJniRuntime.CreationOptions.ThreadDetachCallback, stored per runtime.CreationOptionsand theJniRuntimeconstructor are shipped APIs, so a runtime created without the callback keeps the previous behavior: threads it attaches stay attached when they exit.AndroidRuntime, which both CoreCLR and NativeAOT now use, takes the callback as a constructor parameter and sets it; no other in-tree code constructs aJniRuntime.runtime-environment.ccand callsRuntimeEnvironment::initialize()fromNativeAOT_JNI_OnLoad(), as the CoreCLR host already does. The cleanup needs a cachedJavaVM*, because a pthread key destructor has noJNIEnv*to get one from. The NativeAOT host archive is now compiled with-ffunction-sections -fdata-sections, so the app link's existing--gc-sectionsdrops host code a NativeAOT app never calls, includingRuntimeEnvironment::get_jnienv(), which only CoreCLR uses. See Size impact below.BuildNativeAotWithoutCPlusPlusArchivesforbade anyRuntimeEnvironmentsymbol in a NativeAOT app; that assertion is removed, since the host now links this code on purpose.JniRuntimeconstructor's ownGetEnv()call is folded into_AttachCurrentThread().Alternatives considered:
thread_localdestructor would run even earlier than a pthread key destructor (see below).java.lang.Thread, and local references and thread identity would not survive between calls.Why the detach waits for the last destructor round
The first version detached in the key's first destructor call, and it broke native libraries that still need JNI while the thread exits. When a thread exits, bionic first runs C++
thread_localdestructors andpthread_cleanup_push()handlers. It then runs key destructors in up toPTHREAD_DESTRUCTOR_ITERATIONS(4) rounds. Each round walks the keys in index order; for every key with a non-null value on this thread, it clears the value and calls the destructor. Another round runs only if some destructor stored a new non-null value. The runtime's key is created inJNI_OnLoad, so it usually has a lower index than keys that native libraries create later. Its destructor therefore ran first and detached the thread before the libraries' destructors ran.To test this on real ART, a second probe app has a native library whose own pthread key is created after the runtime's. Each managed worker attaches through Java.Interop and then hands the library some per-thread state:
Variations of the library cover the patterns where this matters:
GetEnv()in the destructor: the code above.JNIEnv*: the destructor uses aJNIEnv*it saved earlier instead of callingGetEnv().Results with 50 workers per mode (API 35 arm64 emulator; counts are library destructors whose JNI call succeeded):
GetEnv(), then JNIJNIEnv*With the cached
JNIEnv*and detach in round 1, CheckJNI aborts the app:So the destructor now waits. The key's value is a round number rather than the
JNIEnv*, which was never read; libc only requires it to be non-null. In rounds 1–3 the destructor stores the next round number and returns. That makes libc call it again in the next round, and ordinary destructors run while the thread is still attached. In the last round it detaches whatever attachment is still current. If another component already detached the thread,GetEnv()returnsJNI_EDETACHEDand there is nothing left to do. If storing the next round number fails, it detaches immediately rather than leak the thread. If another destructor detaches the thread and something re-attaches it during teardown,register_thread_detach()keeps the existing round instead of restarting at 1, which would otherwise run out of rounds before the detach.This is best effort. Nothing reports which destructors are still pending or whether they need JNI, and
DetachCurrentThread()must run on the exiting thread itself, so the last key destructor round is the latest point available. A destructor for a key with a higher index that also re-arms itself until the last round still runs after ours, as the last row shows. That library would also need to stop relying on an attachment it doesn't own.Before API 24, ART used its own pthread key to catch threads that exit while attached, and aborted if the thread was still attached in that key's second round. .NET for Android requires API 24 or newer (
$(AndroidMinimumDotNetApiLevel)).In every mode, the number of Java threads was the same before and after the 50 workers. That includes a library that detaches and re-attaches the thread but never detaches its own attachment; the runtime's last-round detach cleans that up too. A positive control, in which native code attaches each worker before Java.Interop does and never detaches, leaked 50 of 50, which confirms the count detects leaks.
Size impact
Measured on arm64 Release builds of the leak demo app, with the local SDK built once from
main(4d4db7e) and once from this branch. Gzip sizes usegzip -9.mainlib<App>.so, stripped)libnet-android.release.so, stripped)runtime-environment.ccand a cachedJavaVM*. Compiling the host with-ffunction-sections -fdata-sectionslets--gc-sectionsdrop 7 unused host functions, includingRuntimeEnvironment::get_jnienv(); that saves 1,304 bytes, so without it the library would grow by about 2.3 KB.Validation
All on-device runs used an API 35 arm64 emulator (
system-images;android-35;google_apis;arm64-v8a).make prepare CONFIGURATION=Debug && make leeroy CONFIGURATION=Debug: passed../dotnet-local.sh build -t:Install -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:Device=<serial>, then, fromtests/Mono.Android-Tests/Mono.Android-Tests,../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:Device=<serial>: 1,144 passed, 0 failed, 1 skipped.-c Release -p:TestsFlavor=NativeAOT -p:PublishAot=true: 1,080 passed, 0 failed, 2 skipped.libmonodroid.sowas checked against the freshly built runtime before the device runs. An incremental-t:Installhad kept a stale copy, so the test project'sobjandbinwere cleaned first. On NativeAOT, the static runtime library linked into the app was checked for the round-counting destructor.JnienvTest.ManagedThreadIsDetachedOnExitruns under both runtimes. It checks that a worker attached through JNI is no longer alive in the VM after it exits. It fails against a build that never registers the cleanup.TEST_ANDROID_JDK_PATH=~/android-toolchain/jdk-25 ./dotnet-local.sh test bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter FullyQualifiedName~NativeAotBuildTests: 23 passed, includingBuildNativeAotWithoutCPlusPlusArchiveson arm64-v8a, armeabi-v7a and x86_64. After itsRuntimeEnvironmentassertion was removed, that test passed again on all three ABIs.main, which re-enabled several skipped tests ([tests] Re-enable skipped Mono.Android device tests #13757).Not tested: physical devices, Android versions other than API 35, and ABIs other than arm64-v8a.