Skip to content

C# type of Preference trimmed away in Release builds, causing NullReferenceException #9399

Closed

Description

@tipa

Android framework version

net9.0-android

Affected platform version

.NET9 RC2

Description

C# Type seems to be trimmed away, causing problems in Release builds.
The problem did not occur in .NET 8

Steps to Reproduce

In my app I am using a Preference screen, with a SwitchPreferenceCompat specified in the XML.

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
  <PreferenceCategory>
    <SwitchPreferenceCompat app:key="test" app:title="Test"/>
  </PreferenceCategory>
</PreferenceScreen>

In my C# code, I want to get a reference to it in order to initialize:

var test = FindPreference("test") as SwitchPreferenceCompat;
test.PreferenceChange += (_, _) => Toast.MakeText(Context, "toggled", ToastLength.Long).Show();

Example project to reproduce: New folder.zip

Did you find any workaround?

I can use a subclass TwoStatePreference or just Preference instead the as SwitchPreferenceCompat case. I assume that the C# type of SwitchPreferenceCompat was trimmed away because no direct properties or methods of it was accessed (only of it's subclasses)

Relevant log output

No response

Activity

  1. added
    Area: App Runtime
    needs-triage
    on Oct 14, 2024
  2. added
    Area: App+Library Build
    and removed
    Area: App Runtime
    on Oct 14, 2024
  3. jonathanpeppers commented on Oct 14, 2024

    @jonathanpeppers
    Member

    The app specifies TrimMode=full, does the problem go away if you remove this setting? (blank would be TrimMode=partial)

  4. tipa commented on Oct 15, 2024

    @tipa
    Author

    No crash when I remove TrimMode=full. I forgot to mention that I build & deploy the app using dotnet publish -t:Run, it should be easy to reproduce with my example project.
    I was able to resolve the problem in my project easily by casting to another (sub)class, just wanted to make sure you are aware of that edge case. I absolutely love seeing improvements to the trimmer & app size year after year. My app sizes were reduced by another ~20% after migrating to .NET9. Thank you!!

  5. jonathanpeppers commented on Oct 15, 2024

    @jonathanpeppers
    Member

    This also fixes the sample:

    [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(SwitchPreferenceCompat))]
    public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)

    But I'll investigate what we should do here. I suspect the "MarkJavaObjects" trimmer step could need changes here.

  6. jonathanpeppers commented on Oct 15, 2024

    @jonathanpeppers
    Member

    The case is actually similar to a test we have here:

    [Test, TestCaseSource (nameof (NinePatchDrawables))]
    [DynamicDependency (DynamicallyAccessedMemberTypes.All, typeof (NinePatchDrawable))]
    public void DrawableFromRes_ShouldBeTypeNinePatchDrawable (int resId, string name)
    {
    var d = Application.Context.Resources.GetDrawable (resId);
    Assert.IsNotNull (d, $"An image should have been retrieved from resource `{name}`.");
    Assert.IsNotNull (d as NinePatchDrawable, $"The drawable created from resource `{name}` should be a NinePatchDrawable.");
    }

    NinePatchDrawable's constructors weren't preserved, and so we had no way to cast to it from Java via the (IntPtr,JniHandleOwnership) constructor.

  7. removed
    needs-triage
    on Oct 15, 2024
  8. jonathanpeppers commented on Oct 15, 2024

    @jonathanpeppers
    Member

    I've been debugging the trimmer to understand what is happening:

    • Suppose the only usage of a type such as NinePatchDrawable is d as NinePatchDrawable, same as the issue here.

    • The trimmer optimizes this completely away:

    	[Test]
    	[TestCaseSource("NinePatchDrawables")]
    	public void DrawableFromRes_ShouldBeTypeNinePatchDrawable(int resId, string name)
    	{
    		Assert.IsNotNull(Application.Context.Resources.GetDrawable(resId), "An image should have been retrieved from resource `" + name + "`.");
    		Assert.IsNotNull(null, "The drawable created from resource `" + name + "` should be a NinePatchDrawable.");
    	}

    It's literally inlined to null!

    This optimization pass happens during MarkStep, and MarkJavaObjects happens later. We are trying to "preserve any Java objects" that are left after MarkStep, but MarkStep is removing any usage of NinePatchDrawable.

    Unsure what to do here yet, will discuss with our team.

  9. jonathanpeppers commented on Oct 21, 2024

    @jonathanpeppers
    Member

    Another workaround is:

    <PropertyGroup>
      <_ExtraTrimmerArgs>--disable-opt unusedtypechecks $(_ExtraTrimmerArgs)</_ExtraTrimmerArgs>
    </PropertyGroup>

    If a type can be created in Java, this optimization can break.

    We are making this change, as it appears to affect app size only a minor amount: less than our threshold of 5% per file or 3% overall.

  10. locked and limited conversation to collaborators on Nov 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Area: App+Library Build

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions