Repository navigation
[tests] Refresh JNI environment before ThreadReuse diagnostics - #13337
Merged
Merged
Conversation
ThreadReuse deliberately detaches and reattaches a native thread. Logging through Android.Util.Log before GetObject refreshes the cached environment can call JNI NewString through the previous attachment's invalid table. Save the prior environment before the null-instance callback returns, then leave GetObject as the operation under test and log only after it returns. Preserve the old-versus-supplied environment diagnostic, callback rooting, wrapper disposal, and result reporting on the original NUnit test thread. Co-authored-by: Copilot App <[email protected]>
Contributor
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues are identified for the test-only ThreadReuse diagnostic adjustment.
No open issues 🎉
What changed in this PR
This test-only follow-up to #13191 adjusts ThreadReuse diagnostics so JNI logging runs after GetObject refreshes the cached environment following native-thread reattachment.
Changes:
- Capture
JNIEnv.Handleat callback entry, including the initial null-instance callback. - Move JNI logging after
GetObject, retaining the captured handle for comparison. - Preserve the regression operation, ownership, disposal, and original-thread assertion.
| File | Description |
|---|---|
| tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/JnienvTest.cs | Reorders ThreadReuse diagnostics to avoid JNI logging with a stale cached environment. |
Review effort: Balanced
simonrozsival
added a commit
that referenced
this pull request
Oct 31, 2026
Context: #11467 Context: #13190 Prepare the Android runtime for the updated C# memory-safety rules without enabling them in the product. JNI handles and member IDs, callback signatures, borrowed buffers, and VM initialization carry requirements the managed type system cannot establish. Making every managed wrapper unsafe would push those requirements onto callers that cannot discharge them; relying on a method-level `unsafe` modifier alone would leave the implementation proof implicit. Separate the two responsibilities: document and mark APIs whose callers supply raw lifetime, ownership, bounds, thread, or JNI ABI guarantees; keep managed wrappers safe-callable when they establish those guarantees internally. Add local unsafe contexts with concrete `// SAFETY:` explanations, preserving existing dispatch, marshaling, cleanup, and failure paths. ### Runtime contracts and implementation * Cover raw JNI forwarding, callbacks, runtime creation, native imports, collection marshaling, and remapping-table access. Preserve native layouts and distinguish managed storage from native memory: `JValue` stores bits, and the readonly `UnsafeAccessor` methods access typed, GC-tracked managed static fields. * Use `unsafe(...)` for value-producing operations, retain expression-bodied properties and lambdas, and avoid hoisted temporaries. Keep blocks for pinning, multi-step lifetimes, and void calls the current compiler cannot wrap as expression statements. Remove empty handwritten `finally` blocks without removing actual transition or reference cleanup. * Keep JNI generator caller contracts declarative beside each entry, with shared operation-family text and an explicit `RequiresUnsafe` flag. Generate fixed forwarding/pinning proofs instead of constructing prose from parameter names or types. Keep canonical templates and generated callback output synchronized. Product memory-safety `Features` remain off. New unsafe enforcement on 13 raw peer constructors remains deferred to preserve accepted derived initialization chains; the approved Object/Throwable contracts and Throwable None-only route stay intact. Runtime-creation opt-in coverage and the constructor API records remain with activation [#13192](#13192), not this preparation layer. This PR does not close #11467. ### Behavioral fixes tracked independently The audit also exposed existing bugs, which are separated for review: instance/Boolean Spliterator dispatch and Consumer-local cleanup in [#13335](#13335); ThreadReuse diagnostics using a stale JNI environment in [#13337](#13337); checked generic array conversion and owner retention in draft [#13339](#13339); and `Collection.remove(Object)`'s JNI signature in [#13340](#13340). Their working implementations and regressions are still present here pending inheritance of the independent fixes, rather than temporarily restoring known-broken JNI calls. Nullable Java collection elements retain their existing behavior. Related issue context for the ThreadReuse follow-up: #1191 (`ThreadReuse` failing because the native fixture library was missing), #3363 (`NewString()` during logging ending in Java `OutOfMemoryError`), and #7623 (native crashes during `AttachCurrentThread()`). These are related test/JNI reports, not confirmed duplicates of the stale-environment logging SIGSEGV, and this contract-preparation PR does not claim to resolve or close them. The exact diagnostic-ordering bug is documented in #11467 and fixed independently in #13337.
Member
Author
|
@dalexsoto review |
dalexsoto
approved these changes
Nov 4, 2026
dalexsoto
left a comment
Member
There was a problem hiding this comment.
Reviewed the ThreadReuse diagnostic-ordering repair against the native callback fixture, JNI environment cache refresh, wrapper ownership, and current-target test integration. The first callback still seeds the environment cache, and diagnostics now run after GetObject refreshes it. I found no blocking correctness issue in this revision.
simonrozsival
deleted the
simonrozsival-threadreuse-diagnostic-ordering
branch
November 4, 2026 11:16
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Context: #13191
Context: #11467
Java.InteropTests.JnienvTest.ThreadReuse()can crash in its own diagnostic logging before reaching the operation it is supposed to test. The native fixture first calls managed code with a null instance, then detaches the pthread from the JVM, waits for GC, and reattaches before invoking the callback with a Java object. The cachedJNIEnv.Handlecan still refer to the previous attachment;Java.Lang.Object.GetObject()is meant to refresh it before use.Rebuilding the test with the pre-PR logging order reproduced a SIGSEGV on CoreCLR. The first, null-instance callback logged successfully; the second callback crashed while constructing a Java string for
Android.Util.Log.Info(). The captured stack was:This is process termination, not a failed NUnit assertion: instrumentation returned
shortMsg=Process crashed.The logging itself crosses JNI throughNewString()beforeGetObject()can refresh the cached environment.Capture
JNIEnv.Handleat callback entry, before the null-instance early return, so the first callback still seeds the cache. LeaveGetObject(env, instance, DoNotTransfer)as the operation under test, then log the saved handle and supplied environment after it returns. Do not add an eager transition that would bypass the regression. This repairs the existing test; it adds no new test or product-runtime change. The native fixture, ownership, wrapper disposal, callback rooting, and original-thread assertion are unchanged.Related reports: #1191 (
ThreadReusefailing because the native fixture library was missing), #3363 (NewString()during logging ending in JavaOutOfMemoryError), and #7623 (native crashes duringAttachCurrentThread()). These are useful context, not confirmed duplicates of this stale-environment SIGSEGV; this PR does not claim to resolve or close those reports. The exact diagnostic-ordering bug is documented in #11467.Validation
A fresh, user-authorized A/B comparison used CoreCLR Debug,
android-arm64, and one owned API 35 emulator. OnlyJnienvTest.cswas switched between the parent commit's source and this PR's source; both APKs contained byte-identical CoreCLR and native fixture libraries, and their installed APK hashes matched the local artifacts.NewString()SIGSEGV above; no NUnit result was produced.ThreadReusetest with 0 failed/skipped/inconclusive tests.The second fixed run exercised changed-address reattachment and passed the original assertion: saved
JNIEnv.Handle=b400006f0f8459d0, suppliedenv=b400006f0f8570d0. This supersedes the earlier same-address-only coverage limitation.Both variants were built with the following command, using
variant=oldandvariant=fixed;$artifactscontains the temporary exported sources and validation-only targets:Both builds passed with 0 warnings and 0 errors. Because the existing runner cannot select a test by name, the same temporary instrumentation entry point selected the unchanged test through NUnit's exact-name filter with
NumberOfTestWorkers=0:The compile overlay and temporary runner are not part of this PR. Afterward,
./dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -c Debug -v:minimalpassed with 0 warnings and 0 errors, restoring the standard runner. The owned emulator, AVD, and private ADB server were cleaned up; the checkout remains unchanged.SDK preparation also passed:
make prepare, thenmake leeroyto build the extra API levels missing from the firstmake allattempt, followed by a successfulmake allretry. Current-source NativeAOT and broader suites were not run.