Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Documentation/docs-mobile/TOC.yml
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,8 @@
href: messages/xa1037.md
- name: XA1038
href: messages/xa1038.md
- name: XA1050
href: messages/xa1050.md
- name: "XA2xxx: Linker"
items:
- name: "XA2xxx: Linker"
Expand Down
16 changes: 16 additions & 0 deletions Documentation/docs-mobile/building-apps/build-properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -1119,6 +1119,22 @@ r8 dex-compiler and shrinker. The default value is a path into the
.NET for Android workload installation. For further information see our
documentation on [D8 and R8][d8-r8].

## AndroidR8ObfuscationMode

An enum-style property that specifies how `r8` obfuscates Java names when
[`$(AndroidLinkTool)`](#androidlinktool) is `r8`. Supported values are:

- `private-members` preserves Java class and interface names and public or
protected member names. Private and package-private members can be
obfuscated, and R8 optimization is enabled.
- `disabled` disables obfuscation, preserves all Java names, and uses the
non-optimizing Android R8 defaults.

This property does not disable R8 code shrinking.

This property was introduced in a .NET 10 servicing release and defaults to
`disabled` in .NET 10.

## AndroidResgenExtraArgs

Specifies
Expand Down
1 change: 1 addition & 0 deletions Documentation/docs-mobile/messages/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ Either change the value in the AndroidManifest.xml to match the $(SupportedOSPla
+ [XA1039](xa1039.md): The Android Support libraries are not supported in .NET 9 and later, please migrate to AndroidX. See https://aka.ms/xamarin/androidx for more details.
+ [XA1040](xa1040.md): The CoreCLR runtime on Android is an experimental feature and not yet suitable for production use. File issues at: https://github.com/dotnet/android/issues
+ [XA1041](xa1041.md): The MSBuild property 'MonoAndroidAssetPrefix' has an invalid value of 'c:\Foo\Assets'. The value is expected to be a directory path representing the relative location of your Assets or Resources
+ [XA1050](xa1050.md): The 'AndroidR8ObfuscationMode' MSBuild property has an invalid value.

## XA2xxx: Linker

Expand Down
34 changes: 34 additions & 0 deletions Documentation/docs-mobile/messages/xa1050.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
title: .NET for Android error XA1050
description: XA1050 error code
ms.date: 09/10/2026
f1_keywords:
- "XA1050"
---

# .NET for Android error XA1050

## Example messages

```dotnetcli
error XA1050: The 'AndroidR8ObfuscationMode' MSBuild property has an invalid value of 'private-member'. Valid values are 'disabled' and 'private-members'.
```

## Issue

The [`$(AndroidR8ObfuscationMode)`](../building-apps/build-properties.md#androidr8obfuscationmode)
MSBuild property contains an unsupported value. This property is validated when
R8 runs.

## Solution

Set `$(AndroidR8ObfuscationMode)` to one of the supported values:

```xml
<PropertyGroup>
<AndroidR8ObfuscationMode>private-members</AndroidR8ObfuscationMode>
</PropertyGroup>
```

Use `disabled` to preserve all Java names and use the legacy non-optimizing
Android R8 configuration.
1 change: 1 addition & 0 deletions build-tools/installers/create-installers.targets
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)java_runtime_clr.dex" ExcludeFromLegacy="true" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)java_runtime_fastdev_clr.dex" ExcludeFromLegacy="true" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)manifestmerger.jar" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)proguard-android-optimize.txt" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)proguard-android.txt" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)protobuf-net.dll" />
<_MSBuildFiles Include="$(MicrosoftAndroidSdkOutDir)System.CodeDom.dll" />
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Xamarin.Android.Build.Tasks/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,11 @@ To use a custom JDK path for a command line build, set the 'JavaSdkDirectory' MS
{0} - The MSBuild property that has the incorrect value.
{1} - The current value of the property
</comment>
</data>
<data name="XA1050" xml:space="preserve">
<value>The 'AndroidR8ObfuscationMode' MSBuild property has an invalid value of '{0}'. Valid values are 'disabled' and 'private-members'.</value>
<comment>The following are literal names and should not be translated: AndroidR8ObfuscationMode, MSBuild, disabled, private-members.
{0} - The invalid value of the AndroidR8ObfuscationMode MSBuild property.</comment>
</data>
<data name="XA4241" xml:space="preserve">
<value>Java dependency '{0}' is not satisfied.</value>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# This is Xamarin-specific (and enhanced) configuration.

-dontobfuscate

-keep class android.support.multidex.MultiDexApplication { <init>(); }
-keep class net.dot.jni.** { *; <init>(); }
-keep class mono.MonoRuntimeProvider* { *; <init>(...); }
Expand All @@ -22,6 +20,8 @@
-keepclassmembers class md52ce486a14f4bcd95899665e9d932190b.** { *; <init>(...); }

# .NET runtime
# Loaded by name from managed code.
-keep class net.dot.android.ApplicationRegistration { *; }
-keep class net.dot.android.crypto.** { *; <init>(...); }

# Android's template misses fluent setters...
Expand Down
25 changes: 25 additions & 0 deletions src/Xamarin.Android.Build.Tasks/Tasks/R8.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public class R8 : D8
public string? ProguardMappingFileOutput { get; set; }
public string? BuildMetadataFileOutput { get; set; }
public string []? ProguardConfigurationFiles { get; set; }
public string ObfuscationMode { get; set; } = "disabled";

protected override string MainClass => "com.android.tools.r8.R8";

Expand Down Expand Up @@ -116,6 +117,9 @@ protected override string CreateResponseFile ()
}
if (!ProguardCommonXamarinConfiguration.IsNullOrWhiteSpace ()) {
using (var xamcfg = File.CreateText (ProguardCommonXamarinConfiguration)) {
WriteObfuscationRules (xamcfg, ObfuscationMode);
xamcfg.WriteLine ();
xamcfg.Flush ();
GetType ().Assembly.GetManifestResourceStream ("proguard_xamarin.cfg").CopyTo (xamcfg.BaseStream);
if (IgnoreWarnings) {
xamcfg.WriteLine ("-ignorewarnings");
Expand Down Expand Up @@ -165,6 +169,27 @@ protected override string CreateResponseFile ()
return responseFile;
}

internal static void WriteObfuscationRules (TextWriter writer, string obfuscationMode)
{
if (string.Equals (obfuscationMode, "disabled", StringComparison.OrdinalIgnoreCase)) {
writer.WriteLine ("-dontobfuscate");
return;
}
if (!string.Equals (obfuscationMode, "private-members", StringComparison.OrdinalIgnoreCase)) {
throw new ArgumentException ($"Unsupported R8 obfuscation mode '{obfuscationMode}'.", nameof (obfuscationMode));
}

writer.WriteLine ("-keep,allowshrinking,allowoptimization class **");
writer.WriteLine ("-keepclassmembers,allowshrinking,allowoptimization class ** {");
writer.WriteLine (" public protected *;");
writer.WriteLine ("}");
// Managed interface proxy selection observes Class.getInterfaces(), which R8 cannot infer.
writer.WriteLine ("-keep,allowoptimization interface ** {");
writer.WriteLine (" public protected *;");
writer.WriteLine ("}");
writer.WriteLine ("-keep,allowshrinking class * implements **");
}

// Note: We do not want to call the base.LogEventsFromTextOutput as it will incorrectly identify
// Warnings and Info messages as errors.
protected override void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Xamarin.ProjectTools;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;
using System.Xml.Linq;
using Xamarin.Tools.Zip;
Expand All @@ -17,12 +18,18 @@ namespace Xamarin.Android.Build.Tests
public class PackagingTest : BaseTest
{
[Test]
public void CheckR8MetadataFilesExist ()
[TestCase (null, false)]
[TestCase ("disabled", false)]
[TestCase ("private-members", true)]
public void CheckR8MetadataFilesExist (string obfuscationMode, bool optimizationsEnabled)
{
var proj = new XamarinAndroidApplicationProject {
IsRelease = true,
};
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, "r8");
if (obfuscationMode != null) {
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidR8ObfuscationMode, obfuscationMode);
}
// Projects must set $(AndroidCreateProguardMappingFile) to true to opt in
proj.SetProperty (proj.ReleaseProperties, "AndroidCreateProguardMappingFile", true);
proj.SetProperty ("AndroidPackageFormat", "aab");
Expand All @@ -35,7 +42,14 @@ public void CheckR8MetadataFilesExist ()
FileAssert.Exists (aab, $"'{aab}' should have been generated.");
using (var zip = ZipHelper.OpenZip (aab)) {
Assert.IsTrue (zip.Any (e => e.FullName == "BUNDLE-METADATA/com.android.tools.build.obfuscation/proguard.map"), $"AAB file `{aab}` should contain the ProGuard mapping.");
Assert.IsTrue (zip.Any (e => e.FullName == "BUNDLE-METADATA/com.android.tools/r8.json"), $"AAB file `{aab}` should contain the R8 build metadata.");
var metadata = zip.SingleOrDefault (e => e.FullName == "BUNDLE-METADATA/com.android.tools/r8.json");
Assert.IsNotNull (metadata, $"AAB file `{aab}` should contain the R8 build metadata.");
using var stream = new MemoryStream ();
metadata.Extract (stream);
stream.Position = 0;
using var document = JsonDocument.Parse (stream);
var options = document.RootElement.GetProperty ("options");
Assert.AreEqual (optimizationsEnabled, options.GetProperty ("isOptimizationsEnabled").GetBoolean ());
}

Assert.IsTrue (b.Build (proj), "second build should have succeeded.");
Expand All @@ -45,6 +59,43 @@ public void CheckR8MetadataFilesExist ()
}
}

[Test]
public void InvalidR8ObfuscationModeFailsBuild ()
{
var proj = new XamarinAndroidApplicationProject {
IsRelease = true,
};
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, "r8");
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidR8ObfuscationMode, "private-member");

using var builder = CreateApkBuilder ();
builder.ThrowOnBuildFailure = false;
Assert.IsFalse (builder.Build (proj), "Build should reject an invalid AndroidR8ObfuscationMode.");
StringAssertEx.Contains ("error XA1050", builder.LastBuildOutput);
StringAssertEx.Contains ("'private-member'", builder.LastBuildOutput);
}

[TestCase ("", true)]
[TestCase ("r8", false)]
public void InvalidR8ObfuscationModeIsValidatedOnlyForR8 (string linkTool, bool expectedResult)
{
var proj = new XamarinAndroidApplicationProject {
IsRelease = true,
};
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidLinkTool, linkTool);
proj.SetProperty (proj.ReleaseProperties, KnownProperties.AndroidR8ObfuscationMode, "private-member");

using var builder = CreateApkBuilder ();
builder.Target = "_ValidateAndroidR8ObfuscationMode";
builder.ThrowOnBuildFailure = false;
builder.AutomaticNuGetRestore = false;
Assert.AreEqual (expectedResult, builder.Build (proj), "Validation result should depend on whether R8 is enabled.");
if (!expectedResult) {
StringAssertEx.Contains ("error XA1050", builder.LastBuildOutput);
StringAssertEx.Contains ("'private-member'", builder.LastBuildOutput);
}
}

[Test]
public void CheckR8InfoMessagesToNotBreakTheBuild ()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using System.IO;
using NUnit.Framework;
using Xamarin.Android.Tasks;

namespace Xamarin.Android.Build.Tests
{
[TestFixture]
public class R8Tests
{
[Test]
public void WritePrivateMemberObfuscationRules ()
{
using var writer = new StringWriter ();
R8.WriteObfuscationRules (writer, "private-members");

var expected = """
-keep,allowshrinking,allowoptimization class **
-keepclassmembers,allowshrinking,allowoptimization class ** {
public protected *;
}
-keep,allowoptimization interface ** {
public protected *;
}
-keep,allowshrinking class * implements **

""";
Assert.AreEqual (expected.ReplaceLineEndings (Environment.NewLine), writer.ToString ());
Comment thread
jonathanpeppers marked this conversation as resolved.
Resolved
}

[Test]
public void WriteDisabledObfuscationRules ()
{
using var writer = new StringWriter ();
R8.WriteObfuscationRules (writer, "disabled");

Assert.AreEqual ("-dontobfuscate" + Environment.NewLine, writer.ToString ());
}

[Test]
public void WriteInvalidObfuscationModeThrows ()
{
using var writer = new StringWriter ();

Assert.Throws<ArgumentException> (() => R8.WriteObfuscationRules (writer, "private-member"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public static class KnownProperties
public const string AndroidEnableDesugar = "AndroidEnableDesugar";
public const string AndroidManifestMerger = "AndroidManifestMerger";
public const string AndroidLinkTool = "AndroidLinkTool";
public const string AndroidR8ObfuscationMode = "AndroidR8ObfuscationMode";
public const string UseJackAndJill = "UseJackAndJill";
public const string AotAssemblies = "AotAssemblies";
public const string AndroidEnableProfiledAot = "AndroidEnableProfiledAot";
Expand Down
14 changes: 13 additions & 1 deletion src/Xamarin.Android.Build.Tasks/Xamarin.Android.Common.targets
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ Copyright (C) 2011-2012 Xamarin. All rights reserved.
<AndroidEnableDesugar Condition=" '$(AndroidEnableDesugar)' == '' ">False</AndroidEnableDesugar>
<AndroidD8IgnoreWarnings Condition=" '$(AndroidD8IgnoreWarnings)' == '' ">True</AndroidD8IgnoreWarnings>
<AndroidR8IgnoreWarnings Condition=" '$(AndroidR8IgnoreWarnings)' == '' ">True</AndroidR8IgnoreWarnings>
<AndroidR8ObfuscationMode Condition=" '$(AndroidR8ObfuscationMode)' == '' ">disabled</AndroidR8ObfuscationMode>
<AndroidCreateProguardMappingFile Condition="'$(AndroidCreateProguardMappingFile)' == '' And '$(AndroidLinkTool)' == 'r8'">True</AndroidCreateProguardMappingFile>

<!-- Figure out which is the main packaging format we want-->
Expand Down Expand Up @@ -968,6 +969,7 @@ because xbuild doesn't support framework reference assemblies.
<_PropertyCacheItems Include="AndroidEnableProfiledAot=$(AndroidEnableProfiledAot)" />
<_PropertyCacheItems Include="AndroidDexTool=$(AndroidDexTool)" />
<_PropertyCacheItems Include="AndroidLinkTool=$(AndroidLinkTool)" />
<_PropertyCacheItems Include="AndroidR8ObfuscationMode=$(AndroidR8ObfuscationMode)" />
<_PropertyCacheItems Include="AndroidLinkResources=$(AndroidLinkResources)" />
<_PropertyCacheItems Include="AndroidPackageFormat=$(AndroidPackageFormat)" />
<_PropertyCacheItems Include="EmbedAssembliesIntoApk=$(EmbedAssembliesIntoApk)" />
Expand Down Expand Up @@ -2115,7 +2117,8 @@ because xbuild doesn't support framework reference assemblies.
<_ProguardConfiguration Include="$(ProguardConfigFiles)" />
</ItemGroup>
<ItemGroup Condition=" '$(ProguardConfigFiles)' == '' ">
<_ProguardConfiguration Include="$(MSBuildThisFileDirectory)proguard-android.txt" />
<_ProguardConfiguration Include="$(MSBuildThisFileDirectory)proguard-android.txt" Condition=" '$(AndroidR8ObfuscationMode)' == 'disabled' " />
<_ProguardConfiguration Include="$(MSBuildThisFileDirectory)proguard-android-optimize.txt" Condition=" '$(AndroidR8ObfuscationMode)' == 'private-members' " />
<_ProguardConfiguration Include="$(IntermediateOutputPath)proguard\proguard_xamarin.cfg" Condition=" '$(AndroidLinkTool)' != '' " />
<_ProguardConfiguration Include="$(_ProguardProjectConfiguration)" Condition=" '$(AndroidLinkTool)' != '' " />
<_ProguardConfiguration Include="$(IntermediateOutputPath)proguard\proguard_project_primary.cfg" Condition=" '$(AndroidLinkTool)' != '' " />
Expand Down Expand Up @@ -3080,6 +3083,15 @@ because xbuild doesn't support framework reference assemblies.
</CalculateProjectDependencies>
</Target>

<Target Name="_ValidateAndroidR8ObfuscationMode"
BeforeTargets="_CheckForInvalidConfigurationAndPlatform"
Condition=" '$(AndroidLinkTool)' == 'r8' ">
<AndroidError Code="XA1050"
ResourceName="XA1050"
FormatArguments="$(AndroidR8ObfuscationMode)"
Condition=" '$(AndroidR8ObfuscationMode)' != 'disabled' And '$(AndroidR8ObfuscationMode)' != 'private-members' " />
</Target>

<Import Project="$(MSBuildThisFileDirectory)Xamarin.Android.Common.Debugging.targets"
Condition="Exists('$(MSBuildThisFileDirectory)Xamarin.Android.Common.Debugging.targets') And '$(DesignTimeBuild)' != 'true' "/>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Copyright (C) 2018 Xamarin. All rights reserved.
ProguardMappingFileOutput="$(AndroidProguardMappingFile)"
BuildMetadataFileOutput="$(_AndroidR8BuildMetadataFile)"
ProguardConfigurationFiles="@(_ProguardConfiguration)"
ObfuscationMode="$(AndroidR8ObfuscationMode)"
EnableShrinking="$(_R8EnableShrinking)"
EnableMultiDex="$(AndroidEnableMultiDex)"
MultiDexMainDexListFile="$(_AndroidMainDexListFile)"
Expand Down
Loading