Skip to content

[Java.Interop] Detach lazily attached JNI threads on exit - #13801

Open
simonrozsival wants to merge 17 commits into
mainfrom
simonrozsival-ubiquitous-waddle
Open

simonrozsival wants to merge 17 commits into
mainfrom
simonrozsival-ubiquitous-waddle

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 0d8fddcf12d1f7ab4931a77b9bf57791eead657c

Dimension Assessment Rationale
Change confidence 8/10 ↑ Device suites passed with 0 failures on this revision: CoreCLR 1,144; NativeAOT 1,080.
↑ All 23 NativeAotBuildTests pass locally, including the test that failed in CI, on 3 ABIs.
↑ The 7 host functions dropped by --gc-sections are 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).
Diagnosis confidence 9.5/10 ↑ Standalone repro: 5,000 workers left 5,000 Java threads registered; ART aborted with Out of internal thread ids at about 65,500.
↑ The explicit-detach control left 0 threads, isolating the missing detach.
↑ The same demo on this branch leaves 0 threads.
Evidence fit 8/10 ↑ The reported symptom, ART retaining exited threads until it aborts, is reproduced directly by the demo.
↓ 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 with AttachCurrentThread() to call DetachCurrentThread() 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 its java.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:

F DEBUG   : Abort message: 'Out of internal thread ids'
F DEBUG   :       #04 pc 000000000030fe5c  /apex/com.android.art/lib64/libart.so (art::ThreadList::AllocThreadId(art::Thread*)+364)
F DEBUG   :       #05 pc 000000000063c330  /apex/com.android.art/lib64/libart.so (art::Thread::Init(art::ThreadList*, art::JavaVMExt*, art::JNIEnvExt*)+256)
F DEBUG   :       #07 pc 0000000000654fa0  /apex/com.android.art/lib64/libart.so (art::Runtime::AttachCurrentThread(char const*, bool, _jobject*, bool, bool)+132)
F DEBUG   :       #08 pc 0000000000654db4  /apex/com.android.art/lib64/libart.so (art::JII::AttachCurrentThreadInternal(_JavaVM*, _JNIEnv**, void*, bool)+232)

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's java.lang.Thread so it can be counted afterwards:

for (int i = 1; i <= workers; i++) {
	int sequence = i;
	var thread = new Thread (() => {
		// GetEnv() returns JNI_EDETACHED here: the worker starts out unattached.
		probe.Touch (sequence); // JavaSystem.NanoTime () + LeakProbe.touch (sequence): Java.Interop attaches the thread
		if (mode == "detach")
			probe.Detach ();    // control only: JavaVM->DetachCurrentThread () on the same worker
	});
	thread.Start ();
	thread.Join ();
}
public static void touch(int sequence) {
    Thread.currentThread().setName("JniLeak-" + sequence);
}

// Enumerate the root ThreadGroup and count threads whose name starts with "JniLeak-".
public static int countWorkers() { ... }

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:

  • Managed JNI: the code above, with no explicit detach.
  • Explicit detach: the same JNI work, followed by DetachCurrentThread() on the worker.
  • No JNI: the same thread churn, but workers make no JNI calls.

Before this change (.NET 11.0.100-rc.3 CoreCLR, API 35 arm64 emulator, 5,000 workers, mean of two runs per mode):

Mode Named Java workers left Native heap growth RSS growth
No JNI 0 +0.99 MiB +5.93 MiB
Explicit detach 0 +1.02 MiB +6.22 MiB
Managed JNI 5,000 +38.05 MiB +47.87 MiB

Before: 5,000 workers finished, 5,000 named Java workers still registered, 30 Linux threads alive

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() with Out of internal thread ids; that's the stack above. The baseline used the .NET 11 RC 3 SDK; Java.Interop's attach path on main doesn't detach either.

With this change, built from this branch, on the same emulator (5,000 workers, one run per mode):

Mode Named Java workers left Native heap growth RSS growth
No JNI 0 +1.52 MiB +6.43 MiB
Explicit detach 0 +0.43 MiB +5.94 MiB
Managed JNI 0 +0.62 MiB +6.41 MiB

After: 5,000 workers finished, 0 named Java workers left, 27 Linux threads alive

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 added RuntimeEnvironment::register_thread_detach() for threads the host attaches through RuntimeEnvironment::get_jnienv(). Java.Interop now uses the same key for the threads it attaches:

  • JniRuntime._AttachCurrentThread() calls GetEnv() first. Only when that returns JNI_EDETACHED and the subsequent AttachCurrentThread() succeeds does it register the cleanup, so an attachment made by someone else is never claimed.
  • The host passes &RuntimeEnvironment::register_thread_detach to managed code through JnienvInitializeArgs.registerThreadDetach. It reaches Java.Interop as a new, optional JniRuntime.CreationOptions.ThreadDetachCallback, stored per runtime. CreationOptions and the JniRuntime constructor 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 a JniRuntime.
  • The NativeAOT host now builds runtime-environment.cc and calls RuntimeEnvironment::initialize() from NativeAOT_JNI_OnLoad(), as the CoreCLR host already does. The cleanup needs a cached JavaVM*, because a pthread key destructor has no JNIEnv* to get one from. The NativeAOT host archive is now compiled with -ffunction-sections -fdata-sections, so the app link's existing --gc-sections drops host code a NativeAOT app never calls, including RuntimeEnvironment::get_jnienv(), which only CoreCLR uses. See Size impact below. BuildNativeAotWithoutCPlusPlusArchives forbade any RuntimeEnvironment symbol in a NativeAOT app; that assertion is removed, since the host now links this code on purpose.
  • The JniRuntime constructor's own GetEnv() call is folded into _AttachCurrentThread().

Alternatives considered:

  • Detach when the managed thread exits. CoreCLR has no public thread-exit hook. On NativeAOT the only thread-exit callback slot is used by CoreLib. A C++ thread_local destructor would run even earlier than a pthread key destructor (see below).
  • Attach and detach around every outermost JNI call. Every call would create a new 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_local destructors and pthread_cleanup_push() handlers. It then runs key destructors in up to PTHREAD_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 in JNI_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:

var t = new Thread (() => {
	Java.Lang.JavaSystem.NanoTime ();  // Java.Interop attaches the thread and registers the runtime's cleanup
	probe_later_user ();               // the library calls pthread_setspecific (lib_key, state)
});
t.Start ();
t.Join ();
static void lib_destructor (void *state)   // lib_key is created after the runtime's key
{
	JNIEnv *env;
	if ((*vm)->GetEnv (vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
		lost++;                            // the thread was detached under us
		return;
	}
	jclass c = (*env)->FindClass (env, "java/lang/Thread");
	...
	ok++;
}

Variations of the library cover the patterns where this matters:

  • GetEnv() in the destructor: the code above.
  • Cached JNIEnv*: the destructor uses a JNIEnv* it saved earlier instead of calling GetEnv().
  • Detach and re-attach: the library detaches the thread, attaches it again itself, and detaches its own attachment from its destructor.
  • Re-armed destructor: the destructor stores its value again once or three times, so it uses JNI in round 2 or in round 4.

Results with 50 workers per mode (API 35 arm64 emulator; counts are library destructors whose JNI call succeeded):

Library destructor Detach in round 1 (CoreCLR) Detach in last round (CoreCLR) Detach in last round (NativeAOT)
GetEnv(), then JNI 0 / 50 50 / 50 50 / 50
Cached JNIEnv* app aborts 50 / 50 50 / 50
Detach and re-attach 0 / 50 50 / 50 50 / 50
Re-armed once, JNI in round 2 0 / 50 50 / 50 50 / 50
Re-armed three times, JNI in round 4 not run 0 / 50 0 / 50

With the cached JNIEnv* and detach in round 1, CheckJNI aborts the app:

F net.jniteardown: java_vm_ext.cc:598] JNI DETECTED ERROR IN APPLICATION: a thread (tid 5478 is making JNI calls without being attached
F net.jniteardown: java_vm_ext.cc:598]     in call to FindClass
F libc    : Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 5478 (Thread-4), pid 5445 (net.jniteardown)

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() returns JNI_EDETACHED and 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 use gzip -9.

Artifact main This PR Change Change (gzip)
NativeAOT app library (lib<App>.so, stripped) 3,875,936 3,876,936 +1,000 +540
CoreCLR runtime (libnet-android.release.so, stripped) 70,064 70,136 +72 +55
NativeAOT APK 1,778,146 1,778,146 0 +118
CoreCLR APK 6,489,220 6,493,316 +4,096 +1,067
  • NativeAOT grows the most because its host gains the thread-detach code from runtime-environment.cc and a cached JavaVM*. Compiling the host with -ffunction-sections -fdata-sections lets --gc-sections drop 7 unused host functions, including RuntimeEnvironment::get_jnienv(); that saves 1,304 bytes, so without it the library would grow by about 2.3 KB.
  • CoreCLR's host already had the pthread key; only the round counting is new.
  • APK sizes include zip alignment padding, so whole-file changes come in 4 KiB steps; the gzip column tracks the content change.

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.
  • CoreCLR: ./dotnet-local.sh build -t:Install -c Debug tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:Device=<serial>, then, from tests/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.
  • NativeAOT: the same commands with -c Release -p:TestsFlavor=NativeAOT -p:PublishAot=true: 1,080 passed, 0 failed, 2 skipped.
  • The installed test APK's libmonodroid.so was checked against the freshly built runtime before the device runs. An incremental -t:Install had kept a stale copy, so the test project's obj and bin were cleaned first. On NativeAOT, the static runtime library linked into the app was checked for the round-counting destructor.
  • The new JnienvTest.ManagedThreadIsDetachedOnExit runs 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, including BuildNativeAotWithoutCPlusPlusArchives on arm64-v8a, armeabi-v7a and x86_64. After its RuntimeEnvironment assertion was removed, that test passed again on all three ABIs.
  • After the host switched to function sections, the NativeAOT teardown probe gave the same results as before.
  • The device-suite counts above are from the latest merge of main, which re-enabled several skipped tests ([tests] Re-enable skipped Mono.Android device tests #13757).
  • The leak demo and the teardown probe above. Both are standalone apps and are not part of this change.

Not tested: physical devices, Android versions other than API 35, and ABIs other than arm64-v8a.

simonrozsival and others added 6 commits November 25, 2026 22:09
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>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 17:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

@PeppersMuse

Copy link
Copy Markdown

Reviewed as PeppersMuse. No issues found in the change itself.

What I checked:

  • src/Java.Interop/Java.Interop/JniRuntime.cs: _AttachCurrentThread now calls GetEnv first and returns the existing environment when the thread is already attached, so cleanup is only registered when this runtime actually performed the attach — an attachment made by someone else is never claimed. A non-JNI_OK/JNI_EDETACHED GetEnv result throws instead of being silently treated as detached, and a null env from either GetEnv or AttachCurrentThread is now rejected explicitly. The constructor requires the new ThreadDetachCallback and fails fast with ArgumentException when it is missing.
  • The callback plumbing is complete on both paths: CoreCLR passes &RuntimeEnvironment::register_thread_detach through JnienvInitializeArgs.registerThreadDetach (native host) into AndroidRuntime, and NativeAOT passes the same function pointer from NativeAOT_OnInit into JreRuntime. The managed JnienvInitializeArgs field order matches the native struct exactly, and the native static_asserts (offset 88 / size 96 on 64-bit) match the added field.
  • src/native/clr/host/runtime-environment.cc: the pthread-key destructor re-arms through the destructor rounds and only detaches in the last round, so native-library destructors that still need JNI run while the thread is attached; if re-arming fails it falls through and detaches immediately rather than leaking. The final round checks GetEnv first, so a thread another component already detached is left alone. The pre-API-24 ART abort concern does not apply since .NET for Android requires API 24+.
  • The NativeAOT host now calls RuntimeEnvironment::initialize(vm) in JNI_OnLoad and compiles runtime-environment.cc, so the shared cleanup is available there too; the CoreCLR host already initialized it.
  • No in-tree test constructs a real CreationOptions — the only test subclass passes null options and still gets its ArgumentNullException — and no other in-tree code constructs a JniRuntime besides AndroidRuntime and JreRuntime.
  • The validation in the description is unusually thorough (5,000-worker emulator repro: 5,000 leaked Java workers before, 0 after, with the ART 'Out of internal thread ids' abort reproduced at ~65,500 workers on the baseline). One follow-up worth considering, not a blocker: there is no automated regression test in the PR, so that repro only exists as the manual run described here — the exit-time detach behavior would be good to pin down in the test suite.

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 JniRuntime otherwise), and the destructor-round reset scenario is an edge case inside the best-effort behavior the code comment already acknowledges, so I am not repeating either as a defect.

simonrozsival and others added 10 commits November 27, 2026 08:57
…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>
@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants