Skip to content

[tests] Refresh JNI environment before ThreadReuse diagnostics - #13337

Merged
simonrozsival merged 1 commit into
mainfrom
simonrozsival-threadreuse-diagnostic-ordering
Nov 4, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
simonrozsival-threadreuse-diagnostic-ordering

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

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 cached JNIEnv.Handle can 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:

Fatal error.
Got a SIGSEGV while executing native code.
   at Java.Interop.JniNativeMethods.NewString(IntPtr, Char*, Int32)
   at Java.Interop.JniEnvironment+Strings.NewString(Char*, Int32)
   at Java.Interop.JniEnvironment+Strings.NewString(System.String)
   at Android.Runtime.JNIEnv.NewString(System.String)
   at Android.Util.Log.Info(System.String, System.String)
   at Android.Util.Log.Info(System.String, System.String, System.Object[])
   at Java.InteropTests.JnienvTest+<>c__DisplayClass9_0.<ThreadReuse>b__0(IntPtr, IntPtr)

This is process termination, not a failed NUnit assertion: instrumentation returned shortMsg=Process crashed. The logging itself crosses JNI through NewString() before GetObject() can refresh the cached environment.

Capture JNIEnv.Handle at callback entry, before the null-instance early return, so the first callback still seeds the cache. Leave GetObject(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 (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 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. Only JnienvTest.cs was 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.

Test variant Observed result
Pre-PR logging order First attempt terminated with the NewString() SIGSEGV above; no NUnit result was produced.
Fixed logging order Three focused runs passed, each selecting exactly one ThreadReuse test with 0 failed/skipped/inconclusive tests.

The second fixed run exercised changed-address reattachment and passed the original assertion: saved JNIEnv.Handle=b400006f0f8459d0, supplied env=b400006f0f8570d0. This supersedes the earlier same-address-only coverage limitation.

Both variants were built with the following command, using variant=old and variant=fixed; $artifacts contains the temporary exported sources and validation-only targets:

./dotnet-local.sh build tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -c Debug -v:minimal -p:RuntimeIdentifier=android-arm64 -p:EmbedAssembliesIntoApk=true "-p:_ThreadReuseVariant=$variant" "-p:CustomAfterMicrosoftCommonTargets=$artifacts/validation.targets" "-bl:$artifacts/$variant/build.binlog"

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:

adb -P 5091 -s emulator-5670 shell am instrument -w -r Mono.Android.NET_Tests/threadreuse.validation.Instrumentation

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:minimal passed 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, then make leeroy to build the extra API levels missing from the first make all attempt, followed by a successful make all retry. Current-source NativeAOT and broader suites were not run.

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]>
Copilot AI balanced review requested due to automatic review settings October 30, 2026 08:56

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.

🟢 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.Handle at 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.
@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 4, 2026
@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 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
simonrozsival merged commit 81b8f5b into main Nov 4, 2026
42 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-threadreuse-diagnostic-ordering branch November 4, 2026 11:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants