Skip to content

[Java.Interop] Keep JNI reference owners alive during calls - #12754

Merged
simonrozsival merged 1 commit into
mainfrom
jonathanpeppers-jni-owner-lifetimes
Sep 11, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
jonathanpeppers-jni-owner-lifetimes

Conversation

@jonathanpeppers

Copy link
Copy Markdown
Member

Java.Interop.JniObjectReference contains a native handle, not a managed reference to its owner. Copying PeerReference therefore does not keep the wrapper alive while JNI uses that handle.

Retain the source peer through Java.Interop.JavaPeerableExtensions.GetJniTypeName() and JavaAs<TResult>(). The latter can reach GetObjectClass during peer creation before the new peer acquires its own JNI reference.

Also retain the throwable wrapper through JNI Throw in Android.Runtime.AndroidRuntime.RaisePendingException() and Java.Interop.JniEnvironment.Exceptions.Throw(Exception). These methods can create a temporary proxy locally; retaining the original managed exception does not retain that proxy.

The four guards use GC.KeepAlive after the JNI work, matching existing owner-taking helpers such as AndroidEnvironment.RaiseThrowable() and JNIEnv.ToLocalJniHandle(). No array operations or other raw-handle helpers are changed.

These address source-level lifetime gaps identified while investigating #12765. They are not a demonstrated fix for the reported production GetObjectClass crash. No deterministic reproducer or GC-timing regression test is available, and device tests were not run because this worktree has no locally built Android SDK.

Context: #12765 (comment)

Context: #12315

Java.Interop.JniObjectReference contains a native handle, not a managed
reference to its owner.  Retain the source peer while
Java.Interop.JavaPeerableExtensions.GetJniTypeName() looks up its Java
class and JavaAs<TResult>() creates another managed peer.

Also retain the throwable wrapper through JNI Throw in
Android.Runtime.AndroidRuntime.RaisePendingException() and
Java.Interop.JniEnvironment.Exceptions.Throw(Exception).  These paths
can create a temporary proxy that the original managed exception does
not keep alive.

Use GC.KeepAlive after the JNI work, matching existing owner-taking
interop helpers.  These changes address source-level lifetime gaps;
they are not a demonstrated fix for the reported GetObjectClass crash.

Context: https://github.com/dotnet/runtime/issues/132165#issuecomment-5624441077
Context: #12315

Co-authored-by: Copilot App <[email protected]>
Copilot AI lite review requested due to automatic review settings September 10, 2026 20:49

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 new GC.KeepAlive(...) guards should use try/finally to guarantee owner retention on exceptional paths, consistent with established Java.Interop JNI invocation patterns.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR tightens managed lifetime guarantees around borrowed JNI handles by using GC.KeepAlive to ensure the managed owner (or proxy wrapper) isn’t collected while JNI is still consuming the native handle. This is in the Java.Interop/Mono.Android interop layer, where premature collection can surface as intermittent native crashes (e.g., around GetObjectClass/Throw).

Changes:

  • Keep the IJavaPeerable owner alive across GetJniTypeName() and JavaAs<TResult>() JNI usage.
  • Keep the throwable wrapper alive across JNI Throw paths in both Java.Interop and Mono.Android runtime code.
File summaries
File Description
src/Mono.Android/Android.Runtime/AndroidRuntime.cs Keeps the Java throwable wrapper alive through RaisePendingException() JNI throw.
external/Java.Interop/src/Java.Interop/Java.Interop/JniEnvironment.Errors.cs Keeps the proxy Java exception wrapper alive through JniEnvironment.Exceptions.Throw(Exception).
external/Java.Interop/src/Java.Interop/Java.Interop/JavaPeerableExtensions.cs Keeps the peer owner alive across borrowed-handle use in GetJniTypeName() and JavaAs<TResult>().
Review details

Suppressed comments (1)

external/Java.Interop/src/Java.Interop/Java.Interop/JavaPeerableExtensions.cs:52

  • 🤖 ❌ error JNI references — GC.KeepAlive(self) should be in a finally so the keep-alive is guaranteed even if CreatePeer() throws while using the borrowed PeerReference. This matches the established pattern of try { /* JNI */ } finally { GC.KeepAlive(self); } used throughout Java.Interop invoke helpers.
			var peer = JniEnvironment.Runtime.ValueManager.CreatePeer (
					ref r, JniObjectReferenceOptions.Copy,
					targetType: typeof (TResult))
				as TResult;
			GC.KeepAlive (self);
  • Files reviewed: 3/3 changed files
  • Comments generated: 3
  • Review effort level: Lite

@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • azcliprod.blob.core.windows.net

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "azcliprod.blob.core.windows.net"

See Network Configuration for more information.

Generated by Android PR Reviewer for dotnet/runtime#12754

@github-actions github-actions Bot 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.

⚠️ Needs Changes — 0 errors, 1 warning, 0 suggestions.

The added GC.KeepAlive guards correctly protect the four modified JNI uses and match existing straight-line owner-lifetime patterns. One sibling diagnostic path still bypasses the guarded extension and retains the same lifetime hazard; see the inline comment.

CI build #1591605 is still in progress. The Java.Interop test jobs on Windows and macOS and the currently completed checks are passing; the Linux, macOS, and Windows build lanes have not finished.

Warning

Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • azcliprod.blob.core.windows.net

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "azcliprod.blob.core.windows.net"

See Network Configuration for more information.

Generated by Android PR Reviewer for #12754 · copilot · gpt56 · 97.7 AIC · ⌖ 8.72 AIC · ⊞ 21K
Comment /review to run again

@jonathanpeppers jonathanpeppers added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Sep 10, 2026
@simonrozsival
simonrozsival merged commit 9c3fc3d into main Sep 11, 2026
45 checks passed
@simonrozsival
simonrozsival deleted the jonathanpeppers-jni-owner-lifetimes branch September 11, 2026 06:50
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 11, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

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