镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Fix possible premature collection #5405

Closed

Description

@jonpryor

See: https://github.com/xamarin/xamarin-android/blob/f495778d433e45fee2fb61435293f059d6942620/src/Mono.Android/Android.Runtime/JavaObject.cs#L35

The problem with new JavaObject(obj).Handle is that there is a window wherein the JavaObject is collected after the .Handle property is accessed, but before .Handle is returned to Java code, which would "normally" keep the JavaObject instance alive.

Related:

This statement should instead be:

return JNIEnv.ToLocalJniHandle (new JavaObject (obj));

Additionally, JNIEnv.ToLocalJniHandle() needs to add a GC.KeepAlive(): https://github.com/xamarin/xamarin-android/blob/f495778d433e45fee2fb61435293f059d6942620/src/Mono.Android/Android.Runtime/JNIEnv.cs#L746-L754

It should be:

public static IntPtr ToLocalJniHandle (IJavaObject? value)
{
	if (value == null)
		return IntPtr.Zero;
	var ex = value as IJavaObjectEx;
	if (ex != null)
		return ex.ToLocalJniHandle ();
	try {
		return NewLocalRef (value.Handle);
	}
	finally {
		GC.KeepAlive (value);
	}
}

This will ensure that value isn't likewise GC'd immediately after the .Handle access but before NewLocalRef() is invoked.

Activity

  1. jonpryor commented on Dec 10, 2020

    @jonpryor
    ContributorAuthor

    Should likewise audit the rest of the codebase to check for places where GC.KeepAlive() is needed. :-(

  2. jonpryor commented on Dec 18, 2020

    @jonpryor
    ContributorAuthor

    Mono.Android.Export likely needs to be updated to insert GC.KeepAlive() calls in the generated marshal methods.

  3. added a commit that references this issue on Aug 11, 2026
    a5779e9
  4. locked and limited conversation to collaborators on Sep 11, 2026
  5. added 3 commits that reference this issue on Sep 22, 2026
    b9dedec
    6724ca5
    bb74ddd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions